1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
  2 //
  3 // Licensed under the Apache License, Version 2.0 (the "License");
  4 // you may not use this file except in compliance with the License.
  5 // You may obtain a copy of the License at
  6 //
  7 //      http://www.apache.org/licenses/LICENSE-2.0
  8 //
  9 // Unless required by applicable law or agreed to in writing, software
 10 // distributed under the License is distributed on an "AS-IS" BASIS,
 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 12 // See the License for the specific language governing permissions and
 13 // limitations under the License.
 14 
 15 /**
 16  * @fileoverview Bootstrap for the Google JS Library (Closure).
 17  *
 18  * In uncompiled mode base.js will write out Closure's deps file, unless the
 19  * global <code>CLOSURE_NO_DEPS</code> is set to true.  This allows projects to
 20  * include their own deps file(s) from different locations.
 21  *
 22  */
 23 
 24 
 25 /**
 26  * @define {boolean} Overridden to true by the compiler when --closure_pass
 27  *     or --mark_as_compiled is specified.
 28  */
 29 var COMPILED = false;
 30 
 31 
 32 /**
 33  * Base namespace for the Closure library.  Checks to see goog is
 34  * already defined in the current scope before assigning to prevent
 35  * clobbering if base.js is loaded more than once.
 36  *
 37  * @const
 38  */
 39 var goog = goog || {}; // Identifies this file as the Closure base.
 40 
 41 
 42 /**
 43  * Reference to the global context.  In most cases this will be 'window'.
 44  */
 45 goog.global = this;
 46 
 47 
 48 /**
 49  * @define {boolean} DEBUG is provided as a convenience so that debugging code
 50  * that should not be included in a production js_binary can be easily stripped
 51  * by specifying --define goog.DEBUG=false to the JSCompiler. For example, most
 52  * toString() methods should be declared inside an "if (goog.DEBUG)" conditional
 53  * because they are generally used for debugging purposes and it is difficult
 54  * for the JSCompiler to statically determine whether they are used.
 55  */
 56 goog.DEBUG = true;
 57 
 58 
 59 /**
 60  * @define {string} LOCALE defines the locale being used for compilation. It is
 61  * used to select locale specific data to be compiled in js binary. BUILD rule
 62  * can specify this value by "--define goog.LOCALE=<locale_name>" as JSCompiler
 63  * option.
 64  *
 65  * Take into account that the locale code format is important. You should use
 66  * the canonical Unicode format with hyphen as a delimiter. Language must be
 67  * lowercase, Language Script - Capitalized, Region - UPPERCASE.
 68  * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.
 69  *
 70  * See more info about locale codes here:
 71  * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers
 72  *
 73  * For language codes you should use values defined by ISO 693-1. See it here
 74  * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from
 75  * this rule: the Hebrew language. For legacy reasons the old code (iw) should
 76  * be used instead of the new code (he), see http://wiki/Main/IIISynonyms.
 77  */
 78 goog.LOCALE = 'en';  // default to en
 79 
 80 
 81 /**
 82  * Creates object stubs for a namespace.  The presence of one or more
 83  * goog.provide() calls indicate that the file defines the given
 84  * objects/namespaces.  Build tools also scan for provide/require statements
 85  * to discern dependencies, build dependency files (see deps.js), etc.
 86  * @see goog.require
 87  * @param {string} name Namespace provided by this file in the form
 88  *     "goog.package.part".
 89  */
 90 goog.provide = function(name) {
 91   if (!COMPILED) {
 92     // Ensure that the same namespace isn't provided twice. This is intended
 93     // to teach new developers that 'goog.provide' is effectively a variable
 94     // declaration. And when JSCompiler transforms goog.provide into a real
 95     // variable declaration, the compiled JS should work the same as the raw
 96     // JS--even when the raw JS uses goog.provide incorrectly.
 97     if (goog.isProvided_(name)) {
 98       throw Error('Namespace "' + name + '" already declared.');
 99     }
100     delete goog.implicitNamespaces_[name];
101 
102     var namespace = name;
103     while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {
104       if (goog.getObjectByName(namespace)) {
105         break;
106       }
107       goog.implicitNamespaces_[namespace] = true;
108     }
109   }
110 
111   goog.exportPath_(name);
112 };
113 
114 
115 /**
116  * Marks that the current file should only be used for testing, and never for
117  * live code in production.
118  * @param {string=} opt_message Optional message to add to the error that's
119  *     raised when used in production code.
120  */
121 goog.setTestOnly = function(opt_message) {
122   if (COMPILED && !goog.DEBUG) {
123     opt_message = opt_message || '';
124     throw Error('Importing test-only code into non-debug environment' +
125                 opt_message ? ': ' + opt_message : '.');
126   }
127 };
128 
129 
130 if (!COMPILED) {
131 
132   /**
133    * Check if the given name has been goog.provided. This will return false for
134    * names that are available only as implicit namespaces.
135    * @param {string} name name of the object to look for.
136    * @return {boolean} Whether the name has been provided.
137    * @private
138    */
139   goog.isProvided_ = function(name) {
140     return !goog.implicitNamespaces_[name] && !!goog.getObjectByName(name);
141   };
142 
143   /**
144    * Namespaces implicitly defined by goog.provide. For example,
145    * goog.provide('goog.events.Event') implicitly declares
146    * that 'goog' and 'goog.events' must be namespaces.
147    *
148    * @type {Object}
149    * @private
150    */
151   goog.implicitNamespaces_ = {};
152 }
153 
154 
155 /**
156  * Builds an object structure for the provided namespace path,
157  * ensuring that names that already exist are not overwritten. For
158  * example:
159  * "a.b.c" -> a = {};a.b={};a.b.c={};
160  * Used by goog.provide and goog.exportSymbol.
161  * @param {string} name name of the object that this file defines.
162  * @param {*=} opt_object the object to expose at the end of the path.
163  * @param {Object=} opt_objectToExportTo The object to add the path to; default
164  *     is |goog.global|.
165  * @private
166  */
167 goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) {
168   var parts = name.split('.');
169   var cur = opt_objectToExportTo || goog.global;
170 
171   // Internet Explorer exhibits strange behavior when throwing errors from
172   // methods externed in this manner.  See the testExportSymbolExceptions in
173   // base_test.html for an example.
174   if (!(parts[0] in cur) && cur.execScript) {
175     cur.execScript('var ' + parts[0]);
176   }
177 
178   // Certain browsers cannot parse code in the form for((a in b); c;);
179   // This pattern is produced by the JSCompiler when it collapses the
180   // statement above into the conditional loop below. To prevent this from
181   // happening, use a for-loop and reserve the init logic as below.
182 
183   // Parentheses added to eliminate strict JS warning in Firefox.
184   for (var part; parts.length && (part = parts.shift());) {
185     if (!parts.length && goog.isDef(opt_object)) {
186       // last part and we have an object; use it
187       cur[part] = opt_object;
188     } else if (cur[part]) {
189       cur = cur[part];
190     } else {
191       cur = cur[part] = {};
192     }
193   }
194 };
195 
196 
197 /**
198  * Returns an object based on its fully qualified external name.  If you are
199  * using a compilation pass that renames property names beware that using this
200  * function will not find renamed properties.
201  *
202  * @param {string} name The fully qualified name.
203  * @param {Object=} opt_obj The object within which to look; default is
204  *     |goog.global|.
205  * @return {?} The value (object or primitive) or, if not found, null.
206  */
207 goog.getObjectByName = function(name, opt_obj) {
208   var parts = name.split('.');
209   var cur = opt_obj || goog.global;
210   for (var part; part = parts.shift(); ) {
211     if (goog.isDefAndNotNull(cur[part])) {
212       cur = cur[part];
213     } else {
214       return null;
215     }
216   }
217   return cur;
218 };
219 
220 
221 /**
222  * Globalizes a whole namespace, such as goog or goog.lang.
223  *
224  * @param {Object} obj The namespace to globalize.
225  * @param {Object=} opt_global The object to add the properties to.
226  * @deprecated Properties may be explicitly exported to the global scope, but
227  *     this should no longer be done in bulk.
228  */
229 goog.globalize = function(obj, opt_global) {
230   var global = opt_global || goog.global;
231   for (var x in obj) {
232     global[x] = obj[x];
233   }
234 };
235 
236 
237 /**
238  * Adds a dependency from a file to the files it requires.
239  * @param {string} relPath The path to the js file.
240  * @param {Array} provides An array of strings with the names of the objects
241  *                         this file provides.
242  * @param {Array} requires An array of strings with the names of the objects
243  *                         this file requires.
244  */
245 goog.addDependency = function(relPath, provides, requires) {
246   if (!COMPILED) {
247     var provide, require;
248     var path = relPath.replace(/\\/g, '/');
249     var deps = goog.dependencies_;
250     for (var i = 0; provide = provides[i]; i++) {
251       deps.nameToPath[provide] = path;
252       if (!(path in deps.pathToNames)) {
253         deps.pathToNames[path] = {};
254       }
255       deps.pathToNames[path][provide] = true;
256     }
257     for (var j = 0; require = requires[j]; j++) {
258       if (!(path in deps.requires)) {
259         deps.requires[path] = {};
260       }
261       deps.requires[path][require] = true;
262     }
263   }
264 };
265 
266 
267 
268 
269 // NOTE(nnaze): The debug DOM loader was included in base.js as an orignal
270 // way to do "debug-mode" development.  The dependency system can sometimes
271 // be confusing, as can the debug DOM loader's asyncronous nature.
272 //
273 // With the DOM loader, a call to goog.require() is not blocking -- the
274 // script will not load until some point after the current script.  If a
275 // namespace is needed at runtime, it needs to be defined in a previous
276 // script, or loaded via require() with its registered dependencies.
277 // User-defined namespaces may need their own deps file.  See http://go/js_deps,
278 // http://go/genjsdeps, or, externally, DepsWriter.
279 // http://code.google.com/closure/library/docs/depswriter.html
280 //
281 // Because of legacy clients, the DOM loader can't be easily removed from
282 // base.js.  Work is being done to make it disableable or replaceable for
283 // different environments (DOM-less JavaScript interpreters like Rhino or V8,
284 // for example). See bootstrap/ for more information.
285 
286 
287 /**
288  * @define {boolean} Whether to enable the debug loader.
289  *
290  * If enabled, a call to goog.require() will attempt to load the namespace by
291  * appending a script tag to the DOM (if the namespace has been registered).
292  *
293  * If disabled, goog.require() will simply assert that the namespace has been
294  * provided (and depend on the fact that some outside tool correctly ordered
295  * the script).
296  */
297 goog.ENABLE_DEBUG_LOADER = true;
298 
299 
300 /**
301  * Implements a system for the dynamic resolution of dependencies
302  * that works in parallel with the BUILD system. Note that all calls
303  * to goog.require will be stripped by the JSCompiler when the
304  * --closure_pass option is used.
305  * @see goog.provide
306  * @param {string} name Namespace to include (as was given in goog.provide())
307  *     in the form "goog.package.part".
308  */
309 goog.require = function(name) {
310 
311   // if the object already exists we do not need do do anything
312   // TODO(arv): If we start to support require based on file name this has
313   //            to change
314   // TODO(arv): If we allow goog.foo.* this has to change
315   // TODO(arv): If we implement dynamic load after page load we should probably
316   //            not remove this code for the compiled output
317   if (!COMPILED) {
318     if (goog.isProvided_(name)) {
319       return;
320     }
321 
322     if (goog.ENABLE_DEBUG_LOADER) {
323       var path = goog.getPathFromDeps_(name);
324       if (path) {
325         goog.included_[path] = true;
326         goog.writeScripts_();
327         return;
328       }
329     }
330 
331     var errorMessage = 'goog.require could not find: ' + name;
332     if (goog.global.console) {
333       goog.global.console['error'](errorMessage);
334     }
335 
336 
337       throw Error(errorMessage);
338 
339   }
340 };
341 
342 
343 /**
344  * Path for included scripts
345  * @type {string}
346  */
347 goog.basePath = '';
348 
349 
350 /**
351  * A hook for overriding the base path.
352  * @type {string|undefined}
353  */
354 goog.global.CLOSURE_BASE_PATH;
355 
356 
357 /**
358  * Whether to write out Closure's deps file. By default,
359  * the deps are written.
360  * @type {boolean|undefined}
361  */
362 goog.global.CLOSURE_NO_DEPS;
363 
364 
365 /**
366  * A function to import a single script. This is meant to be overridden when
367  * Closure is being run in non-HTML contexts, such as web workers. It's defined
368  * in the global scope so that it can be set before base.js is loaded, which
369  * allows deps.js to be imported properly.
370  *
371  * The function is passed the script source, which is a relative URI. It should
372  * return true if the script was imported, false otherwise.
373  */
374 goog.global.CLOSURE_IMPORT_SCRIPT;
375 
376 
377 /**
378  * Null function used for default values of callbacks, etc.
379  * @return {void} Nothing.
380  */
381 goog.nullFunction = function() {};
382 
383 
384 /**
385  * The identity function. Returns its first argument.
386  *
387  * @param {*=} opt_returnValue The single value that will be returned.
388  * @param {...*} var_args Optional trailing arguments. These are ignored.
389  * @return {?} The first argument. We can't know the type -- just pass it along
390  *      without type.
391  * @deprecated Use goog.functions.identity instead.
392  */
393 goog.identityFunction = function(opt_returnValue, var_args) {
394   return opt_returnValue;
395 };
396 
397 
398 /**
399  * When defining a class Foo with an abstract method bar(), you can do:
400  *
401  * Foo.prototype.bar = goog.abstractMethod
402  *
403  * Now if a subclass of Foo fails to override bar(), an error
404  * will be thrown when bar() is invoked.
405  *
406  * Note: This does not take the name of the function to override as
407  * an argument because that would make it more difficult to obfuscate
408  * our JavaScript code.
409  *
410  * @type {!Function}
411  * @throws {Error} when invoked to indicate the method should be
412  *   overridden.
413  */
414 goog.abstractMethod = function() {
415   throw Error('unimplemented abstract method');
416 };
417 
418 
419 /**
420  * Adds a {@code getInstance} static method that always return the same instance
421  * object.
422  * @param {!Function} ctor The constructor for the class to add the static
423  *     method to.
424  */
425 goog.addSingletonGetter = function(ctor) {
426   ctor.getInstance = function() {
427     if (ctor.instance_) {
428       return ctor.instance_;
429     }
430     if (goog.DEBUG) {
431       // NOTE: JSCompiler can't optimize away Array#push.
432       goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;
433     }
434     return ctor.instance_ = new ctor;
435   };
436 };
437 
438 
439 /**
440  * All singleton classes that have been instantiated, for testing. Don't read
441  * it directly, use the {@code goog.testing.singleton} module. The compiler
442  * removes this variable if unused.
443  * @type {!Array.<!Function>}
444  * @private
445  */
446 goog.instantiatedSingletons_ = [];
447 
448 
449 if (!COMPILED && goog.ENABLE_DEBUG_LOADER) {
450   /**
451    * Object used to keep track of urls that have already been added. This
452    * record allows the prevention of circular dependencies.
453    * @type {Object}
454    * @private
455    */
456   goog.included_ = {};
457 
458 
459   /**
460    * This object is used to keep track of dependencies and other data that is
461    * used for loading scripts
462    * @private
463    * @type {Object}
464    */
465   goog.dependencies_ = {
466     pathToNames: {}, // 1 to many
467     nameToPath: {}, // 1 to 1
468     requires: {}, // 1 to many
469     // used when resolving dependencies to prevent us from
470     // visiting the file twice
471     visited: {},
472     written: {} // used to keep track of script files we have written
473   };
474 
475 
476   /**
477    * Tries to detect whether is in the context of an HTML document.
478    * @return {boolean} True if it looks like HTML document.
479    * @private
480    */
481   goog.inHtmlDocument_ = function() {
482     var doc = goog.global.document;
483     return typeof doc != 'undefined' &&
484            'write' in doc;  // XULDocument misses write.
485   };
486 
487 
488   /**
489    * Tries to detect the base path of the base.js script that bootstraps Closure
490    * @private
491    */
492   goog.findBasePath_ = function() {
493     if (goog.global.CLOSURE_BASE_PATH) {
494       goog.basePath = goog.global.CLOSURE_BASE_PATH;
495       return;
496     } else if (!goog.inHtmlDocument_()) {
497       return;
498     }
499     var doc = goog.global.document;
500     var scripts = doc.getElementsByTagName('script');
501     // Search backwards since the current script is in almost all cases the one
502     // that has base.js.
503     for (var i = scripts.length - 1; i >= 0; --i) {
504       var src = scripts[i].src;
505       var qmark = src.lastIndexOf('?');
506       var l = qmark == -1 ? src.length : qmark;
507       if (src.substr(l - 7, 7) == 'base.js') {
508         goog.basePath = src.substr(0, l - 7);
509         return;
510       }
511     }
512   };
513 
514 
515   /**
516    * Imports a script if, and only if, that script hasn't already been imported.
517    * (Must be called at execution time)
518    * @param {string} src Script source.
519    * @private
520    */
521   goog.importScript_ = function(src) {
522     var importScript = goog.global.CLOSURE_IMPORT_SCRIPT ||
523         goog.writeScriptTag_;
524     if (!goog.dependencies_.written[src] && importScript(src)) {
525       goog.dependencies_.written[src] = true;
526     }
527   };
528 
529 
530   /**
531    * The default implementation of the import function. Writes a script tag to
532    * import the script.
533    *
534    * @param {string} src The script source.
535    * @return {boolean} True if the script was imported, false otherwise.
536    * @private
537    */
538   goog.writeScriptTag_ = function(src) {
539     if (goog.inHtmlDocument_()) {
540       var doc = goog.global.document;
541       doc.write(
542           '<script type="text/javascript" src="' + src + '"></' + 'script>');
543       return true;
544     } else {
545       return false;
546     }
547   };
548 
549 
550   /**
551    * Resolves dependencies based on the dependencies added using addDependency
552    * and calls importScript_ in the correct order.
553    * @private
554    */
555   goog.writeScripts_ = function() {
556     // the scripts we need to write this time
557     var scripts = [];
558     var seenScript = {};
559     var deps = goog.dependencies_;
560 
561     function visitNode(path) {
562       if (path in deps.written) {
563         return;
564       }
565 
566       // we have already visited this one. We can get here if we have cyclic
567       // dependencies
568       if (path in deps.visited) {
569         if (!(path in seenScript)) {
570           seenScript[path] = true;
571           scripts.push(path);
572         }
573         return;
574       }
575 
576       deps.visited[path] = true;
577 
578       if (path in deps.requires) {
579         for (var requireName in deps.requires[path]) {
580           // If the required name is defined, we assume that it was already
581           // bootstrapped by other means.
582           if (!goog.isProvided_(requireName)) {
583             if (requireName in deps.nameToPath) {
584               visitNode(deps.nameToPath[requireName]);
585             } else {
586               throw Error('Undefined nameToPath for ' + requireName);
587             }
588           }
589         }
590       }
591 
592       if (!(path in seenScript)) {
593         seenScript[path] = true;
594         scripts.push(path);
595       }
596     }
597 
598     for (var path in goog.included_) {
599       if (!deps.written[path]) {
600         visitNode(path);
601       }
602     }
603 
604     for (var i = 0; i < scripts.length; i++) {
605       if (scripts[i]) {
606         goog.importScript_(goog.basePath + scripts[i]);
607       } else {
608         throw Error('Undefined script input');
609       }
610     }
611   };
612 
613 
614   /**
615    * Looks at the dependency rules and tries to determine the script file that
616    * fulfills a particular rule.
617    * @param {string} rule In the form goog.namespace.Class or project.script.
618    * @return {?string} Url corresponding to the rule, or null.
619    * @private
620    */
621   goog.getPathFromDeps_ = function(rule) {
622     if (rule in goog.dependencies_.nameToPath) {
623       return goog.dependencies_.nameToPath[rule];
624     } else {
625       return null;
626     }
627   };
628 
629   goog.findBasePath_();
630 
631   // Allow projects to manage the deps files themselves.
632  /* if (!goog.global.CLOSURE_NO_DEPS) {
633     goog.importScript_(goog.basePath + 'deps.js');
634   }*/
635 }
636 
637 
638 
639 //==============================================================================
640 // Language Enhancements
641 //==============================================================================
642 
643 
644 /**
645  * This is a "fixed" version of the typeof operator.  It differs from the typeof
646  * operator in such a way that null returns 'null' and arrays return 'array'.
647  * @param {*} value The value to get the type of.
648  * @return {string} The name of the type.
649  */
650 goog.typeOf = function(value) {
651   var s = typeof value;
652   if (s == 'object') {
653     if (value) {
654       // Check these first, so we can avoid calling Object.prototype.toString if
655       // possible.
656       //
657       // IE improperly marshals tyepof across execution contexts, but a
658       // cross-context object will still return false for "instanceof Object".
659       if (value instanceof Array) {
660         return 'array';
661       } else if (value instanceof Object) {
662         return s;
663       }
664 
665       // HACK: In order to use an Object prototype method on the arbitrary
666       //   value, the compiler requires the value be cast to type Object,
667       //   even though the ECMA spec explicitly allows it.
668       var className = Object.prototype.toString.call(
669           /** @type {Object} */ (value));
670       // In Firefox 3.6, attempting to access iframe window objects' length
671       // property throws an NS_ERROR_FAILURE, so we need to special-case it
672       // here.
673       if (className == '[object Window]') {
674         return 'object';
675       }
676 
677       // We cannot always use constructor == Array or instanceof Array because
678       // different frames have different Array objects. In IE6, if the iframe
679       // where the array was created is destroyed, the array loses its
680       // prototype. Then dereferencing val.splice here throws an exception, so
681       // we can't use goog.isFunction. Calling typeof directly returns 'unknown'
682       // so that will work. In this case, this function will return false and
683       // most array functions will still work because the array is still
684       // array-like (supports length and []) even though it has lost its
685       // prototype.
686       // Mark Miller noticed that Object.prototype.toString
687       // allows access to the unforgeable [[Class]] property.
688       //  15.2.4.2 Object.prototype.toString ( )
689       //  When the toString method is called, the following steps are taken:
690       //      1. Get the [[Class]] property of this object.
691       //      2. Compute a string value by concatenating the three strings
692       //         "[object ", Result(1), and "]".
693       //      3. Return Result(2).
694       // and this behavior survives the destruction of the execution context.
695       if ((className == '[object Array]' ||
696            // In IE all non value types are wrapped as objects across window
697            // boundaries (not iframe though) so we have to do object detection
698            // for this edge case
699            typeof value.length == 'number' &&
700            typeof value.splice != 'undefined' &&
701            typeof value.propertyIsEnumerable != 'undefined' &&
702            !value.propertyIsEnumerable('splice')
703 
704           )) {
705         return 'array';
706       }
707       // HACK: There is still an array case that fails.
708       //     function ArrayImpostor() {}
709       //     ArrayImpostor.prototype = [];
710       //     var impostor = new ArrayImpostor;
711       // this can be fixed by getting rid of the fast path
712       // (value instanceof Array) and solely relying on
713       // (value && Object.prototype.toString.vall(value) === '[object Array]')
714       // but that would require many more function calls and is not warranted
715       // unless closure code is receiving objects from untrusted sources.
716 
717       // IE in cross-window calls does not correctly marshal the function type
718       // (it appears just as an object) so we cannot use just typeof val ==
719       // 'function'. However, if the object has a call property, it is a
720       // function.
721       if ((className == '[object Function]' ||
722           typeof value.call != 'undefined' &&
723           typeof value.propertyIsEnumerable != 'undefined' &&
724           !value.propertyIsEnumerable('call'))) {
725         return 'function';
726       }
727 
728 
729     } else {
730       return 'null';
731     }
732 
733   } else if (s == 'function' && typeof value.call == 'undefined') {
734     // In Safari typeof nodeList returns 'function', and on Firefox
735     // typeof behaves similarly for HTML{Applet,Embed,Object}Elements
736     // and RegExps.  We would like to return object for those and we can
737     // detect an invalid function by making sure that the function
738     // object has a call method.
739     return 'object';
740   }
741   return s;
742 };
743 
744 
745 /**
746  * Returns true if the specified value is not |undefined|.
747  * WARNING: Do not use this to test if an object has a property. Use the in
748  * operator instead.  Additionally, this function assumes that the global
749  * undefined variable has not been redefined.
750  * @param {*} val Variable to test.
751  * @return {boolean} Whether variable is defined.
752  */
753 goog.isDef = function(val) {
754   return val !== undefined;
755 };
756 
757 
758 /**
759  * Returns true if the specified value is |null|
760  * @param {*} val Variable to test.
761  * @return {boolean} Whether variable is null.
762  */
763 goog.isNull = function(val) {
764   return val === null;
765 };
766 
767 
768 /**
769  * Returns true if the specified value is defined and not null
770  * @param {*} val Variable to test.
771  * @return {boolean} Whether variable is defined and not null.
772  */
773 goog.isDefAndNotNull = function(val) {
774   // Note that undefined == null.
775   return val != null;
776 };
777 
778 
779 /**
780  * Returns true if the specified value is an array
781  * @param {*} val Variable to test.
782  * @return {boolean} Whether variable is an array.
783  */
784 goog.isArray = function(val) {
785   return goog.typeOf(val) == 'array';
786 };
787 
788 
789 /**
790  * Returns true if the object looks like an array. To qualify as array like
791  * the value needs to be either a NodeList or an object with a Number length
792  * property.
793  * @param {*} val Variable to test.
794  * @return {boolean} Whether variable is an array.
795  */
796 goog.isArrayLike = function(val) {
797   var type = goog.typeOf(val);
798   return type == 'array' || type == 'object' && typeof val.length == 'number';
799 };
800 
801 
802 /**
803  * Returns true if the object looks like a Date. To qualify as Date-like
804  * the value needs to be an object and have a getFullYear() function.
805  * @param {*} val Variable to test.
806  * @return {boolean} Whether variable is a like a Date.
807  */
808 goog.isDateLike = function(val) {
809   return goog.isObject(val) && typeof val.getFullYear == 'function';
810 };
811 
812 
813 /**
814  * Returns true if the specified value is a string
815  * @param {*} val Variable to test.
816  * @return {boolean} Whether variable is a string.
817  */
818 goog.isString = function(val) {
819   return typeof val == 'string';
820 };
821 
822 
823 /**
824  * Returns true if the specified value is a boolean
825  * @param {*} val Variable to test.
826  * @return {boolean} Whether variable is boolean.
827  */
828 goog.isBoolean = function(val) {
829   return typeof val == 'boolean';
830 };
831 
832 
833 /**
834  * Returns true if the specified value is a number
835  * @param {*} val Variable to test.
836  * @return {boolean} Whether variable is a number.
837  */
838 goog.isNumber = function(val) {
839   return typeof val == 'number';
840 };
841 
842 
843 /**
844  * Returns true if the specified value is a function
845  * @param {*} val Variable to test.
846  * @return {boolean} Whether variable is a function.
847  */
848 goog.isFunction = function(val) {
849   return goog.typeOf(val) == 'function';
850 };
851 
852 
853 /**
854  * Returns true if the specified value is an object.  This includes arrays
855  * and functions.
856  * @param {*} val Variable to test.
857  * @return {boolean} Whether variable is an object.
858  */
859 goog.isObject = function(val) {
860   var type = typeof val;
861   return type == 'object' && val != null || type == 'function';
862   // return Object(val) === val also works, but is slower, especially if val is
863   // not an object.
864 };
865 
866 
867 /**
868  * Gets a unique ID for an object. This mutates the object so that further
869  * calls with the same object as a parameter returns the same value. The unique
870  * ID is guaranteed to be unique across the current session amongst objects that
871  * are passed into {@code getUid}. There is no guarantee that the ID is unique
872  * or consistent across sessions. It is unsafe to generate unique ID for
873  * function prototypes.
874  *
875  * @param {Object} obj The object to get the unique ID for.
876  * @return {number} The unique ID for the object.
877  */
878 goog.getUid = function(obj) {
879   // TODO(arv): Make the type stricter, do not accept null.
880 
881   // In Opera window.hasOwnProperty exists but always returns false so we avoid
882   // using it. As a consequence the unique ID generated for BaseClass.prototype
883   // and SubClass.prototype will be the same.
884   return obj[goog.UID_PROPERTY_] ||
885       (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);
886 };
887 
888 
889 /**
890  * Removes the unique ID from an object. This is useful if the object was
891  * previously mutated using {@code goog.getUid} in which case the mutation is
892  * undone.
893  * @param {Object} obj The object to remove the unique ID field from.
894  */
895 goog.removeUid = function(obj) {
896   // TODO(arv): Make the type stricter, do not accept null.
897 
898   // DOM nodes in IE are not instance of Object and throws exception
899   // for delete. Instead we try to use removeAttribute
900   if ('removeAttribute' in obj) {
901     obj.removeAttribute(goog.UID_PROPERTY_);
902   }
903   /** @preserveTry */
904   try {
905     delete obj[goog.UID_PROPERTY_];
906   } catch (ex) {
907   }
908 };
909 
910 
911 /**
912  * Name for unique ID property. Initialized in a way to help avoid collisions
913  * with other closure javascript on the same page.
914  * @type {string}
915  * @private
916  */
917 goog.UID_PROPERTY_ = 'closure_uid_' +
918     Math.floor(Math.random() * 2147483648).toString(36);
919 
920 
921 /**
922  * Counter for UID.
923  * @type {number}
924  * @private
925  */
926 goog.uidCounter_ = 0;
927 
928 
929 /**
930  * Adds a hash code field to an object. The hash code is unique for the
931  * given object.
932  * @param {Object} obj The object to get the hash code for.
933  * @return {number} The hash code for the object.
934  * @deprecated Use goog.getUid instead.
935  */
936 goog.getHashCode = goog.getUid;
937 
938 
939 /**
940  * Removes the hash code field from an object.
941  * @param {Object} obj The object to remove the field from.
942  * @deprecated Use goog.removeUid instead.
943  */
944 goog.removeHashCode = goog.removeUid;
945 
946 
947 /**
948  * Clones a value. The input may be an Object, Array, or basic type. Objects and
949  * arrays will be cloned recursively.
950  *
951  * WARNINGS:
952  * <code>goog.cloneObject</code> does not detect reference loops. Objects that
953  * refer to themselves will cause infinite recursion.
954  *
955  * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies
956  * UIDs created by <code>getUid</code> into cloned results.
957  *
958  * @param {*} obj The value to clone.
959  * @return {*} A clone of the input value.
960  * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.
961  */
962 goog.cloneObject = function(obj) {
963   var type = goog.typeOf(obj);
964   if (type == 'object' || type == 'array') {
965     if (obj.clone) {
966       return obj.clone();
967     }
968     var clone = type == 'array' ? [] : {};
969     for (var key in obj) {
970       clone[key] = goog.cloneObject(obj[key]);
971     }
972     return clone;
973   }
974 
975   return obj;
976 };
977 
978 
979 /**
980  * A native implementation of goog.bind.
981  * @param {Function} fn A function to partially apply.
982  * @param {Object|undefined} selfObj Specifies the object which |this| should
983  *     point to when the function is run.
984  * @param {...*} var_args Additional arguments that are partially
985  *     applied to the function.
986  * @return {!Function} A partially-applied form of the function bind() was
987  *     invoked as a method of.
988  * @private
989  * @suppress {deprecated} The compiler thinks that Function.prototype.bind
990  *     is deprecated because some people have declared a pure-JS version.
991  *     Only the pure-JS version is truly deprecated.
992  */
993 goog.bindNative_ = function(fn, selfObj, var_args) {
994   return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));
995 };
996 
997 
998 /**
999  * A pure-JS implementation of goog.bind.
1000  * @param {Function} fn A function to partially apply.
1001  * @param {Object|undefined} selfObj Specifies the object which |this| should
1002  *     point to when the function is run.
1003  * @param {...*} var_args Additional arguments that are partially
1004  *     applied to the function.
1005  * @return {!Function} A partially-applied form of the function bind() was
1006  *     invoked as a method of.
1007  * @private
1008  */
1009 goog.bindJs_ = function(fn, selfObj, var_args) {
1010   if (!fn) {
1011     throw new Error();
1012   }
1013 
1014   if (arguments.length > 2) {
1015     var boundArgs = Array.prototype.slice.call(arguments, 2);
1016     return function() {
1017       // Prepend the bound arguments to the current arguments.
1018       var newArgs = Array.prototype.slice.call(arguments);
1019       Array.prototype.unshift.apply(newArgs, boundArgs);
1020       return fn.apply(selfObj, newArgs);
1021     };
1022 
1023   } else {
1024     return function() {
1025       return fn.apply(selfObj, arguments);
1026     };
1027   }
1028 };
1029 
1030 
1031 /**
1032  * Partially applies this function to a particular 'this object' and zero or
1033  * more arguments. The result is a new function with some arguments of the first
1034  * function pre-filled and the value of |this| 'pre-specified'.<br><br>
1035  *
1036  * Remaining arguments specified at call-time are appended to the pre-
1037  * specified ones.<br><br>
1038  *
1039  * Also see: {@link #partial}.<br><br>
1040  *
1041  * Usage:
1042  * <pre>var barMethBound = bind(myFunction, myObj, 'arg1', 'arg2');
1043  * barMethBound('arg3', 'arg4');</pre>
1044  *
1045  * @param {Function} fn A function to partially apply.
1046  * @param {Object|undefined} selfObj Specifies the object which |this| should
1047  *     point to when the function is run.
1048  * @param {...*} var_args Additional arguments that are partially
1049  *     applied to the function.
1050  * @return {!Function} A partially-applied form of the function bind() was
1051  *     invoked as a method of.
1052  * @suppress {deprecated} See above.
1053  */
1054 goog.bind = function(fn, selfObj, var_args) {
1055   // TODO(nicksantos): narrow the type signature.
1056   if (Function.prototype.bind &&
1057       // NOTE(nicksantos): Somebody pulled base.js into the default
1058       // Chrome extension environment. This means that for Chrome extensions,
1059       // they get the implementation of Function.prototype.bind that
1060       // calls goog.bind instead of the native one. Even worse, we don't want
1061       // to introduce a circular dependency between goog.bind and
1062       // Function.prototype.bind, so we have to hack this to make sure it
1063       // works correctly.
1064       Function.prototype.bind.toString().indexOf('native code') != -1) {
1065     goog.bind = goog.bindNative_;
1066   } else {
1067     goog.bind = goog.bindJs_;
1068   }
1069   return goog.bind.apply(null, arguments);
1070 };
1071 
1072 
1073 /**
1074  * Like bind(), except that a 'this object' is not required. Useful when the
1075  * target function is already bound.
1076  *
1077  * Usage:
1078  * var g = partial(f, arg1, arg2);
1079  * g(arg3, arg4);
1080  *
1081  * @param {Function} fn A function to partially apply.
1082  * @param {...*} var_args Additional arguments that are partially
1083  *     applied to fn.
1084  * @return {!Function} A partially-applied form of the function bind() was
1085  *     invoked as a method of.
1086  */
1087 goog.partial = function(fn, var_args) {
1088   var args = Array.prototype.slice.call(arguments, 1);
1089   return function() {
1090     // Prepend the bound arguments to the current arguments.
1091     var newArgs = Array.prototype.slice.call(arguments);
1092     newArgs.unshift.apply(newArgs, args);
1093     return fn.apply(this, newArgs);
1094   };
1095 };
1096 
1097 
1098 /**
1099  * Copies all the members of a source object to a target object. This method
1100  * does not work on all browsers for all objects that contain keys such as
1101  * toString or hasOwnProperty. Use goog.object.extend for this purpose.
1102  * @param {Object} target Target.
1103  * @param {Object} source Source.
1104  */
1105 goog.mixin = function(target, source) {
1106   for (var x in source) {
1107     target[x] = source[x];
1108   }
1109 
1110   // For IE7 or lower, the for-in-loop does not contain any properties that are
1111   // not enumerable on the prototype object (for example, isPrototypeOf from
1112   // Object.prototype) but also it will not include 'replace' on objects that
1113   // extend String and change 'replace' (not that it is common for anyone to
1114   // extend anything except Object).
1115 };
1116 
1117 
1118 /**
1119  * @return {number} An integer value representing the number of milliseconds
1120  *     between midnight, January 1, 1970 and the current time.
1121  */
1122 goog.now = Date.now || (function() {
1123   // Unary plus operator converts its operand to a number which in the case of
1124   // a date is done by calling getTime().
1125   return +new Date();
1126 });
1127 
1128 
1129 /**
1130  * Evals javascript in the global scope.  In IE this uses execScript, other
1131  * browsers use goog.global.eval. If goog.global.eval does not evaluate in the
1132  * global scope (for example, in Safari), appends a script tag instead.
1133  * Throws an exception if neither execScript or eval is defined.
1134  * @param {string} script JavaScript string.
1135  */
1136 goog.globalEval = function(script) {
1137   if (goog.global.execScript) {
1138     goog.global.execScript(script, 'JavaScript');
1139   } else if (goog.global.eval) {
1140     // Test to see if eval works
1141     if (goog.evalWorksForGlobals_ == null) {
1142       goog.global.eval('var _et_ = 1;');
1143       if (typeof goog.global['_et_'] != 'undefined') {
1144         delete goog.global['_et_'];
1145         goog.evalWorksForGlobals_ = true;
1146       } else {
1147         goog.evalWorksForGlobals_ = false;
1148       }
1149     }
1150 
1151     if (goog.evalWorksForGlobals_) {
1152       goog.global.eval(script);
1153     } else {
1154       var doc = goog.global.document;
1155       var scriptElt = doc.createElement('script');
1156       scriptElt.type = 'text/javascript';
1157       scriptElt.defer = false;
1158       // Note(user): can't use .innerHTML since "t('<test>')" will fail and
1159       // .text doesn't work in Safari 2.  Therefore we append a text node.
1160       scriptElt.appendChild(doc.createTextNode(script));
1161       doc.body.appendChild(scriptElt);
1162       doc.body.removeChild(scriptElt);
1163     }
1164   } else {
1165     throw Error('goog.globalEval not available');
1166   }
1167 };
1168 
1169 
1170 /**
1171  * Indicates whether or not we can call 'eval' directly to eval code in the
1172  * global scope. Set to a Boolean by the first call to goog.globalEval (which
1173  * empirically tests whether eval works for globals). @see goog.globalEval
1174  * @type {?boolean}
1175  * @private
1176  */
1177 goog.evalWorksForGlobals_ = null;
1178 
1179 
1180 /**
1181  * Optional map of CSS class names to obfuscated names used with
1182  * goog.getCssName().
1183  * @type {Object|undefined}
1184  * @private
1185  * @see goog.setCssNameMapping
1186  */
1187 goog.cssNameMapping_;
1188 
1189 
1190 /**
1191  * Optional obfuscation style for CSS class names. Should be set to either
1192  * 'BY_WHOLE' or 'BY_PART' if defined.
1193  * @type {string|undefined}
1194  * @private
1195  * @see goog.setCssNameMapping
1196  */
1197 goog.cssNameMappingStyle_;
1198 
1199 
1200 /**
1201  * Handles strings that are intended to be used as CSS class names.
1202  *
1203  * This function works in tandem with @see goog.setCssNameMapping.
1204  *
1205  * Without any mapping set, the arguments are simple joined with a
1206  * hyphen and passed through unaltered.
1207  *
1208  * When there is a mapping, there are two possible styles in which
1209  * these mappings are used. In the BY_PART style, each part (i.e. in
1210  * between hyphens) of the passed in css name is rewritten according
1211  * to the map. In the BY_WHOLE style, the full css name is looked up in
1212  * the map directly. If a rewrite is not specified by the map, the
1213  * compiler will output a warning.
1214  *
1215  * When the mapping is passed to the compiler, it will replace calls
1216  * to goog.getCssName with the strings from the mapping, e.g.
1217  *     var x = goog.getCssName('foo');
1218  *     var y = goog.getCssName(this.baseClass, 'active');
1219  *  becomes:
1220  *     var x= 'foo';
1221  *     var y = this.baseClass + '-active';
1222  *
1223  * If one argument is passed it will be processed, if two are passed
1224  * only the modifier will be processed, as it is assumed the first
1225  * argument was generated as a result of calling goog.getCssName.
1226  *
1227  * @param {string} className The class name.
1228  * @param {string=} opt_modifier A modifier to be appended to the class name.
1229  * @return {string} The class name or the concatenation of the class name and
1230  *     the modifier.
1231  */
1232 goog.getCssName = function(className, opt_modifier) {
1233   var getMapping = function(cssName) {
1234     return goog.cssNameMapping_[cssName] || cssName;
1235   };
1236 
1237   var renameByParts = function(cssName) {
1238     // Remap all the parts individually.
1239     var parts = cssName.split('-');
1240     var mapped = [];
1241     for (var i = 0; i < parts.length; i++) {
1242       mapped.push(getMapping(parts[i]));
1243     }
1244     return mapped.join('-');
1245   };
1246 
1247   var rename;
1248   if (goog.cssNameMapping_) {
1249     rename = goog.cssNameMappingStyle_ == 'BY_WHOLE' ?
1250         getMapping : renameByParts;
1251   } else {
1252     rename = function(a) {
1253       return a;
1254     };
1255   }
1256 
1257   if (opt_modifier) {
1258     return className + '-' + rename(opt_modifier);
1259   } else {
1260     return rename(className);
1261   }
1262 };
1263 
1264 
1265 /**
1266  * Sets the map to check when returning a value from goog.getCssName(). Example:
1267  * <pre>
1268  * goog.setCssNameMapping({
1269  *   "goog": "a",
1270  *   "disabled": "b",
1271  * });
1272  *
1273  * var x = goog.getCssName('goog');
1274  * // The following evaluates to: "a a-b".
1275  * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')
1276  * </pre>
1277  * When declared as a map of string literals to string literals, the JSCompiler
1278  * will replace all calls to goog.getCssName() using the supplied map if the
1279  * --closure_pass flag is set.
1280  *
1281  * @param {!Object} mapping A map of strings to strings where keys are possible
1282  *     arguments to goog.getCssName() and values are the corresponding values
1283  *     that should be returned.
1284  * @param {string=} opt_style The style of css name mapping. There are two valid
1285  *     options: 'BY_PART', and 'BY_WHOLE'.
1286  * @see goog.getCssName for a description.
1287  */
1288 goog.setCssNameMapping = function(mapping, opt_style) {
1289   goog.cssNameMapping_ = mapping;
1290   goog.cssNameMappingStyle_ = opt_style;
1291 };
1292 
1293 
1294 /**
1295  * To use CSS renaming in compiled mode, one of the input files should have a
1296  * call to goog.setCssNameMapping() with an object literal that the JSCompiler
1297  * can extract and use to replace all calls to goog.getCssName(). In uncompiled
1298  * mode, JavaScript code should be loaded before this base.js file that declares
1299  * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is
1300  * to ensure that the mapping is loaded before any calls to goog.getCssName()
1301  * are made in uncompiled mode.
1302  *
1303  * A hook for overriding the CSS name mapping.
1304  * @type {Object|undefined}
1305  */
1306 goog.global.CLOSURE_CSS_NAME_MAPPING;
1307 
1308 
1309 if (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {
1310   // This does not call goog.setCssNameMapping() because the JSCompiler
1311   // requires that goog.setCssNameMapping() be called with an object literal.
1312   goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;
1313 }
1314 
1315 
1316 /**
1317  * Abstract implementation of goog.getMsg for use with localized messages.
1318  * @param {string} str Translatable string, places holders in the form {$foo}.
1319  * @param {Object=} opt_values Map of place holder name to value.
1320  * @return {string} message with placeholders filled.
1321  */
1322 goog.getMsg = function(str, opt_values) {
1323   var values = opt_values || {};
1324   for (var key in values) {
1325     var value = ('' + values[key]).replace(/\$/g, '$$$$');
1326     str = str.replace(new RegExp('\\{\\$' + key + '\\}', 'gi'), value);
1327   }
1328   return str;
1329 };
1330 
1331 
1332 /**
1333  * Exposes an unobfuscated global namespace path for the given object.
1334  * Note that fields of the exported object *will* be obfuscated,
1335  * unless they are exported in turn via this function or
1336  * goog.exportProperty
1337  *
1338  * <p>Also handy for making public items that are defined in anonymous
1339  * closures.
1340  *
1341  * ex. goog.exportSymbol('public.path.Foo', Foo);
1342  *
1343  * ex. goog.exportSymbol('public.path.Foo.staticFunction',
1344  *                       Foo.staticFunction);
1345  *     public.path.Foo.staticFunction();
1346  *
1347  * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',
1348  *                       Foo.prototype.myMethod);
1349  *     new public.path.Foo().myMethod();
1350  *
1351  * @param {string} publicPath Unobfuscated name to export.
1352  * @param {*} object Object the name should point to.
1353  * @param {Object=} opt_objectToExportTo The object to add the path to; default
1354  *     is |goog.global|.
1355  */
1356 goog.exportSymbol = function(publicPath, object, opt_objectToExportTo) {
1357   goog.exportPath_(publicPath, object, opt_objectToExportTo);
1358 };
1359 
1360 
1361 /**
1362  * Exports a property unobfuscated into the object's namespace.
1363  * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);
1364  * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);
1365  * @param {Object} object Object whose static property is being exported.
1366  * @param {string} publicName Unobfuscated name to export.
1367  * @param {*} symbol Object the name should point to.
1368  */
1369 goog.exportProperty = function(object, publicName, symbol) {
1370   object[publicName] = symbol;
1371 };
1372 
1373 
1374 /**
1375  * Inherit the prototype methods from one constructor into another.
1376  *
1377  * Usage:
1378  * <pre>
1379  * function ParentClass(a, b) { }
1380  * ParentClass.prototype.foo = function(a) { }
1381  *
1382  * function ChildClass(a, b, c) {
1383  *   goog.base(this, a, b);
1384  * }
1385  * goog.inherits(ChildClass, ParentClass);
1386  *
1387  * var child = new ChildClass('a', 'b', 'see');
1388  * child.foo(); // works
1389  * </pre>
1390  *
1391  * In addition, a superclass' implementation of a method can be invoked
1392  * as follows:
1393  *
1394  * <pre>
1395  * ChildClass.prototype.foo = function(a) {
1396  *   ChildClass.superClass_.foo.call(this, a);
1397  *   // other code
1398  * };
1399  * </pre>
1400  *
1401  * @param {Function} childCtor Child class.
1402  * @param {Function} parentCtor Parent class.
1403  */
1404 goog.inherits = function(childCtor, parentCtor) {
1405   /** @constructor */
1406   function tempCtor() {};
1407   tempCtor.prototype = parentCtor.prototype;
1408   childCtor.superClass_ = parentCtor.prototype;
1409   childCtor.prototype = new tempCtor();
1410   /** @override */
1411   childCtor.prototype.constructor = childCtor;
1412 };
1413 
1414 
1415 /**
1416  * Call up to the superclass.
1417  *
1418  * If this is called from a constructor, then this calls the superclass
1419  * contructor with arguments 1-N.
1420  *
1421  * If this is called from a prototype method, then you must pass
1422  * the name of the method as the second argument to this function. If
1423  * you do not, you will get a runtime error. This calls the superclass'
1424  * method with arguments 2-N.
1425  *
1426  * This function only works if you use goog.inherits to express
1427  * inheritance relationships between your classes.
1428  *
1429  * This function is a compiler primitive. At compile-time, the
1430  * compiler will do macro expansion to remove a lot of
1431  * the extra overhead that this function introduces. The compiler
1432  * will also enforce a lot of the assumptions that this function
1433  * makes, and treat it as a compiler error if you break them.
1434  *
1435  * @param {!Object} me Should always be "this".
1436  * @param {*=} opt_methodName The method name if calling a super method.
1437  * @param {...*} var_args The rest of the arguments.
1438  * @return {*} The return value of the superclass method.
1439  */
1440 goog.base = function(me, opt_methodName, var_args) {
1441   var caller = arguments.callee.caller;
1442   if (caller.superClass_) {
1443     // This is a constructor. Call the superclass constructor.
1444     return caller.superClass_.constructor.apply(
1445         me, Array.prototype.slice.call(arguments, 1));
1446   }
1447 
1448   var args = Array.prototype.slice.call(arguments, 2);
1449   var foundCaller = false;
1450   for (var ctor = me.constructor;
1451        ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) {
1452     if (ctor.prototype[opt_methodName] === caller) {
1453       foundCaller = true;
1454     } else if (foundCaller) {
1455       return ctor.prototype[opt_methodName].apply(me, args);
1456     }
1457   }
1458 
1459   // If we did not find the caller in the prototype chain,
1460   // then one of two things happened:
1461   // 1) The caller is an instance method.
1462   // 2) This method was not called by the right caller.
1463   if (me[opt_methodName] === caller) {
1464     return me.constructor.prototype[opt_methodName].apply(me, args);
1465   } else {
1466     throw Error(
1467         'goog.base called from a method of one name ' +
1468         'to a method of a different name');
1469   }
1470 };
1471 
1472 
1473 /**
1474  * Allow for aliasing within scope functions.  This function exists for
1475  * uncompiled code - in compiled code the calls will be inlined and the
1476  * aliases applied.  In uncompiled code the function is simply run since the
1477  * aliases as written are valid JavaScript.
1478  * @param {function()} fn Function to call.  This function can contain aliases
1479  *     to namespaces (e.g. "var dom = goog.dom") or classes
1480  *    (e.g. "var Timer = goog.Timer").
1481  */
1482 goog.scope = function(fn) {
1483   fn.call(goog.global);
1484 };
1485 /*! jQuery v1.7.1 jquery.com | jquery.org/license */
1486 (function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cb(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function ca(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bE.test(a)?d(a,e):ca(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)ca(a+"["+e+"]",b[e],c,d);else d(a,b)}function b_(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function b$(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bT,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bP),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bC(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bx:by,g=0,h=e.length;if(d>0){if(c!=="border")for(;g<h;g++)c||(d-=parseFloat(f.css(a,"padding"+e[g]))||0),c==="margin"?d+=parseFloat(f.css(a,c+e[g]))||0:d-=parseFloat(f.css(a,"border"+e[g]+"Width"))||0;return d+"px"}d=bz(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0;if(c)for(;g<h;g++)d+=parseFloat(f.css(a,"padding"+e[g]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+e[g]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+e[g]))||0);return d+"px"}function bp(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p,q=c.createElement("div"),r=c.documentElement;q.setAttribute("className","t"),q.innerHTML="   <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="<div style='width:4px;'></div>",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h<g;h++)e=d[h],e&&(c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};
1487 f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=[],j,k,l,m,n,o,p,q,r,s,t;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click")){m=f(this),m.context=this.ownerDocument||this;for(l=c.target;l!=this;l=l.parentNode||this){o={},q=[],m[0]=l;for(j=0;j<e;j++)r=d[j],s=r.selector,o[s]===b&&(o[s]=r.quick?H(l,r.quick):m.is(s)),o[s]&&q.push(r);q.length&&i.push({elem:l,matches:q})}}d.length>e&&i.push({elem:this,matches:d.slice(e)});for(j=0;j<i.length&&!c.isPropagationStopped();j++){p=i[j],c.currentTarget=p.elem;for(k=0;k<p.matches.length&&!c.isImmediatePropagationStopped();k++){r=p.matches[k];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=((f.event.special[r.origType]||{}).handle||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.POS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function()
1488 {for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bp)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bn(k[i]);else bn(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bq=/alpha\([^)]*\)/i,br=/opacity=([^)]*)/,bs=/([A-Z]|^ms)/g,bt=/^-?\d+(?:px)?$/i,bu=/^-?\d/,bv=/^([\-+])=([\-+.\de]+)/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bv.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bz)return bz(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bC(a,b,d);f.swap(a,bw,function(){e=bC(a,b,d)});return e}},set:function(a,b){if(!bt.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cv(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cu("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cu("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cv(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cn.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=co.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cr||cs(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cp&&(cp=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cr||cs(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cp),cp=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
1489 /**
1490  * jQuery.ScrollTo - Easy element scrolling using jQuery.
1491  * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
1492  * Dual licensed under MIT and GPL.
1493  * Date: 5/25/2009
1494  * @author Ariel Flesler
1495  * @version 1.4.2
1496  *
1497  * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
1498  */
1499 ;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
1500 /*! jQuery UI - v1.8.21 - 2012-06-05
1501 * https://github.com/jquery/jquery-ui
1502 * Includes: jquery.ui.core.js
1503 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1504 (function(a,b){function c(b,c){var e=b.nodeName.toLowerCase();if("area"===e){var f=b.parentNode,g=f.name,h;return!b.href||!g||f.nodeName.toLowerCase()!=="map"?!1:(h=a("img[usemap=#"+g+"]")[0],!!h&&d(h))}return(/input|select|textarea|button|object/.test(e)?!b.disabled:"a"==e?b.href||c:c)&&d(b)}function d(b){return!a(b).parents().andSelf().filter(function(){return a.curCSS(this,"visibility")==="hidden"||a.expr.filters.hidden(this)}).length}a.ui=a.ui||{};if(a.ui.version)return;a.extend(a.ui,{version:"1.8.21",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}}),a.fn.extend({propAttr:a.fn.prop||a.fn.attr,_focus:a.fn.focus,focus:function(b,c){return typeof b=="number"?this.each(function(){var d=this;setTimeout(function(){a(d).focus(),c&&c.call(d)},b)}):this._focus.apply(this,arguments)},scrollParent:function(){var b;return a.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?b=this.parents().filter(function(){return/(relative|absolute|fixed)/.test(a.curCSS(this,"position",1))&&/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0):b=this.parents().filter(function(){return/(auto|scroll)/.test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0),/fixed/.test(this.css("position"))||!b.length?a(document):b},zIndex:function(c){if(c!==b)return this.css("zIndex",c);if(this.length){var d=a(this[0]),e,f;while(d.length&&d[0]!==document){e=d.css("position");if(e==="absolute"||e==="relative"||e==="fixed"){f=parseInt(d.css("zIndex"),10);if(!isNaN(f)&&f!==0)return f}d=d.parent()}}return 0},disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(a){a.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),a.each(["Width","Height"],function(c,d){function h(b,c,d,f){return a.each(e,function(){c-=parseFloat(a.curCSS(b,"padding"+this,!0))||0,d&&(c-=parseFloat(a.curCSS(b,"border"+this+"Width",!0))||0),f&&(c-=parseFloat(a.curCSS(b,"margin"+this,!0))||0)}),c}var e=d==="Width"?["Left","Right"]:["Top","Bottom"],f=d.toLowerCase(),g={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};a.fn["inner"+d]=function(c){return c===b?g["inner"+d].call(this):this.each(function(){a(this).css(f,h(this,c)+"px")})},a.fn["outer"+d]=function(b,c){return typeof b!="number"?g["outer"+d].call(this,b):this.each(function(){a(this).css(f,h(this,b,!0,c)+"px")})}}),a.extend(a.expr[":"],{data:function(b,c,d){return!!a.data(b,d[3])},focusable:function(b){return c(b,!isNaN(a.attr(b,"tabindex")))},tabbable:function(b){var d=a.attr(b,"tabindex"),e=isNaN(d);return(e||d>=0)&&c(b,!e)}}),a(function(){var b=document.body,c=b.appendChild(c=document.createElement("div"));c.offsetHeight,a.extend(c.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0}),a.support.minHeight=c.offsetHeight===100,a.support.selectstart="onselectstart"in c,b.removeChild(c).style.display="none"}),a.extend(a.ui,{plugin:{add:function(b,c,d){var e=a.ui[b].prototype;for(var f in d)e.plugins[f]=e.plugins[f]||[],e.plugins[f].push([c,d[f]])},call:function(a,b,c){var d=a.plugins[b];if(!d||!a.element[0].parentNode)return;for(var e=0;e<d.length;e++)a.options[d[e][0]]&&d[e][1].apply(a.element,c)}},contains:function(a,b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(b,c){if(a(b).css("overflow")==="hidden")return!1;var d=c&&c==="left"?"scrollLeft":"scrollTop",e=!1;return b[d]>0?!0:(b[d]=1,e=b[d]>0,b[d]=0,e)},isOverAxis:function(a,b,c){return a>b&&a<b+c},isOver:function(b,c,d,e,f,g){return a.ui.isOverAxis(b,d,f)&&a.ui.isOverAxis(c,e,g)}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1505 * https://github.com/jquery/jquery-ui
1506 * Includes: jquery.ui.widget.js
1507 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1508 (function(a,b){if(a.cleanData){var c=a.cleanData;a.cleanData=function(b){for(var d=0,e;(e=b[d])!=null;d++)try{a(e).triggerHandler("remove")}catch(f){}c(b)}}else{var d=a.fn.remove;a.fn.remove=function(b,c){return this.each(function(){return c||(!b||a.filter(b,[this]).length)&&a("*",this).add([this]).each(function(){try{a(this).triggerHandler("remove")}catch(b){}}),d.call(a(this),b,c)})}}a.widget=function(b,c,d){var e=b.split(".")[0],f;b=b.split(".")[1],f=e+"-"+b,d||(d=c,c=a.Widget),a.expr[":"][f]=function(c){return!!a.data(c,b)},a[e]=a[e]||{},a[e][b]=function(a,b){arguments.length&&this._createWidget(a,b)};var g=new c;g.options=a.extend(!0,{},g.options),a[e][b].prototype=a.extend(!0,g,{namespace:e,widgetName:b,widgetEventPrefix:a[e][b].prototype.widgetEventPrefix||b,widgetBaseClass:f},d),a.widget.bridge(b,a[e][b])},a.widget.bridge=function(c,d){a.fn[c]=function(e){var f=typeof e=="string",g=Array.prototype.slice.call(arguments,1),h=this;return e=!f&&g.length?a.extend.apply(null,[!0,e].concat(g)):e,f&&e.charAt(0)==="_"?h:(f?this.each(function(){var d=a.data(this,c),f=d&&a.isFunction(d[e])?d[e].apply(d,g):d;if(f!==d&&f!==b)return h=f,!1}):this.each(function(){var b=a.data(this,c);b?b.option(e||{})._init():a.data(this,c,new d(e,this))}),h)}},a.Widget=function(a,b){arguments.length&&this._createWidget(a,b)},a.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(b,c){a.data(c,this.widgetName,this),this.element=a(c),this.options=a.extend(!0,{},this.options,this._getCreateOptions(),b);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()}),this._create(),this._trigger("create"),this._init()},_getCreateOptions:function(){return a.metadata&&a.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName),this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled "+"ui-state-disabled")},widget:function(){return this.element},option:function(c,d){var e=c;if(arguments.length===0)return a.extend({},this.options);if(typeof c=="string"){if(d===b)return this.options[c];e={},e[c]=d}return this._setOptions(e),this},_setOptions:function(b){var c=this;return a.each(b,function(a,b){c._setOption(a,b)}),this},_setOption:function(a,b){return this.options[a]=b,a==="disabled"&&this.widget()[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled"+" "+"ui-state-disabled").attr("aria-disabled",b),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(b,c,d){var e,f,g=this.options[b];d=d||{},c=a.Event(c),c.type=(b===this.widgetEventPrefix?b:this.widgetEventPrefix+b).toLowerCase(),c.target=this.element[0],f=c.originalEvent;if(f)for(e in f)e in c||(c[e]=f[e]);return this.element.trigger(c,d),!(a.isFunction(g)&&g.call(this.element[0],c,d)===!1||c.isDefaultPrevented())}}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1509 * https://github.com/jquery/jquery-ui
1510 * Includes: jquery.ui.mouse.js
1511 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1512 (function(a,b){var c=!1;a(document).mouseup(function(a){c=!1}),a.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var b=this;this.element.bind("mousedown."+this.widgetName,function(a){return b._mouseDown(a)}).bind("click."+this.widgetName,function(c){if(!0===a.data(c.target,b.widgetName+".preventClickEvent"))return a.removeData(c.target,b.widgetName+".preventClickEvent"),c.stopImmediatePropagation(),!1}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(b){if(c)return;this._mouseStarted&&this._mouseUp(b),this._mouseDownEvent=b;var d=this,e=b.which==1,f=typeof this.options.cancel=="string"&&b.target.nodeName?a(b.target).closest(this.options.cancel).length:!1;if(!e||f||!this._mouseCapture(b))return!0;this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){d.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)){this._mouseStarted=this._mouseStart(b)!==!1;if(!this._mouseStarted)return b.preventDefault(),!0}return!0===a.data(b.target,this.widgetName+".preventClickEvent")&&a.removeData(b.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(a){return d._mouseMove(a)},this._mouseUpDelegate=function(a){return d._mouseUp(a)},a(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),b.preventDefault(),c=!0,!0},_mouseMove:function(b){return!a.browser.msie||document.documentMode>=9||!!b.button?this._mouseStarted?(this._mouseDrag(b),b.preventDefault()):(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,b)!==!1,this._mouseStarted?this._mouseDrag(b):this._mouseUp(b)),!this._mouseStarted):this._mouseUp(b)},_mouseUp:function(b){return a(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,b.target==this._mouseDownEvent.target&&a.data(b.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(b)),!1},_mouseDistanceMet:function(a){return Math.max(Math.abs(this._mouseDownEvent.pageX-a.pageX),Math.abs(this._mouseDownEvent.pageY-a.pageY))>=this.options.distance},_mouseDelayMet:function(a){return this.mouseDelayMet},_mouseStart:function(a){},_mouseDrag:function(a){},_mouseStop:function(a){},_mouseCapture:function(a){return!0}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1513 * https://github.com/jquery/jquery-ui
1514 * Includes: jquery.ui.position.js
1515 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1516 (function(a,b){a.ui=a.ui||{};var c=/left|center|right/,d=/top|center|bottom/,e="center",f={},g=a.fn.position,h=a.fn.offset;a.fn.position=function(b){if(!b||!b.of)return g.apply(this,arguments);b=a.extend({},b);var h=a(b.of),i=h[0],j=(b.collision||"flip").split(" "),k=b.offset?b.offset.split(" "):[0,0],l,m,n;return i.nodeType===9?(l=h.width(),m=h.height(),n={top:0,left:0}):i.setTimeout?(l=h.width(),m=h.height(),n={top:h.scrollTop(),left:h.scrollLeft()}):i.preventDefault?(b.at="left top",l=m=0,n={top:b.of.pageY,left:b.of.pageX}):(l=h.outerWidth(),m=h.outerHeight(),n=h.offset()),a.each(["my","at"],function(){var a=(b[this]||"").split(" ");a.length===1&&(a=c.test(a[0])?a.concat([e]):d.test(a[0])?[e].concat(a):[e,e]),a[0]=c.test(a[0])?a[0]:e,a[1]=d.test(a[1])?a[1]:e,b[this]=a}),j.length===1&&(j[1]=j[0]),k[0]=parseInt(k[0],10)||0,k.length===1&&(k[1]=k[0]),k[1]=parseInt(k[1],10)||0,b.at[0]==="right"?n.left+=l:b.at[0]===e&&(n.left+=l/2),b.at[1]==="bottom"?n.top+=m:b.at[1]===e&&(n.top+=m/2),n.left+=k[0],n.top+=k[1],this.each(function(){var c=a(this),d=c.outerWidth(),g=c.outerHeight(),h=parseInt(a.curCSS(this,"marginLeft",!0))||0,i=parseInt(a.curCSS(this,"marginTop",!0))||0,o=d+h+(parseInt(a.curCSS(this,"marginRight",!0))||0),p=g+i+(parseInt(a.curCSS(this,"marginBottom",!0))||0),q=a.extend({},n),r;b.my[0]==="right"?q.left-=d:b.my[0]===e&&(q.left-=d/2),b.my[1]==="bottom"?q.top-=g:b.my[1]===e&&(q.top-=g/2),f.fractions||(q.left=Math.round(q.left),q.top=Math.round(q.top)),r={left:q.left-h,top:q.top-i},a.each(["left","top"],function(c,e){a.ui.position[j[c]]&&a.ui.position[j[c]][e](q,{targetWidth:l,targetHeight:m,elemWidth:d,elemHeight:g,collisionPosition:r,collisionWidth:o,collisionHeight:p,offset:k,my:b.my,at:b.at})}),a.fn.bgiframe&&c.bgiframe(),c.offset(a.extend(q,{using:b.using}))})},a.ui.position={fit:{left:function(b,c){var d=a(window),e=c.collisionPosition.left+c.collisionWidth-d.width()-d.scrollLeft();b.left=e>0?b.left-e:Math.max(b.left-c.collisionPosition.left,b.left)},top:function(b,c){var d=a(window),e=c.collisionPosition.top+c.collisionHeight-d.height()-d.scrollTop();b.top=e>0?b.top-e:Math.max(b.top-c.collisionPosition.top,b.top)}},flip:{left:function(b,c){if(c.at[0]===e)return;var d=a(window),f=c.collisionPosition.left+c.collisionWidth-d.width()-d.scrollLeft(),g=c.my[0]==="left"?-c.elemWidth:c.my[0]==="right"?c.elemWidth:0,h=c.at[0]==="left"?c.targetWidth:-c.targetWidth,i=-2*c.offset[0];b.left+=c.collisionPosition.left<0?g+h+i:f>0?g+h+i:0},top:function(b,c){if(c.at[1]===e)return;var d=a(window),f=c.collisionPosition.top+c.collisionHeight-d.height()-d.scrollTop(),g=c.my[1]==="top"?-c.elemHeight:c.my[1]==="bottom"?c.elemHeight:0,h=c.at[1]==="top"?c.targetHeight:-c.targetHeight,i=-2*c.offset[1];b.top+=c.collisionPosition.top<0?g+h+i:f>0?g+h+i:0}}},a.offset.setOffset||(a.offset.setOffset=function(b,c){/static/.test(a.curCSS(b,"position"))&&(b.style.position="relative");var d=a(b),e=d.offset(),f=parseInt(a.curCSS(b,"top",!0),10)||0,g=parseInt(a.curCSS(b,"left",!0),10)||0,h={top:c.top-e.top+f,left:c.left-e.left+g};"using"in c?c.using.call(b,h):d.css(h)},a.fn.offset=function(b){var c=this[0];return!c||!c.ownerDocument?null:b?a.isFunction(b)?this.each(function(c){a(this).offset(b.call(this,c,a(this).offset()))}):this.each(function(){a.offset.setOffset(this,b)}):h.call(this)}),function(){var b=document.getElementsByTagName("body")[0],c=document.createElement("div"),d,e,g,h,i;d=document.createElement(b?"div":"body"),g={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},b&&a.extend(g,{position:"absolute",left:"-1000px",top:"-1000px"});for(var j in g)d.style[j]=g[j];d.appendChild(c),e=b||document.documentElement,e.insertBefore(d,e.firstChild),c.style.cssText="position: absolute; left: 10.7432222px; top: 10.432325px; height: 30px; width: 201px;",h=a(c).offset(function(a,b){return b}).offset(),d.innerHTML="",e.removeChild(d),i=h.top+h.left+(b?2e3:0),f.fractions=i>21&&i<22}()})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1517 * https://github.com/jquery/jquery-ui
1518 * Includes: jquery.ui.draggable.js
1519 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1520 (function(a,b){a.widget("ui.draggable",a.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){this.options.helper=="original"&&!/^(?:r|a|f)/.test(this.element.css("position"))&&(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},destroy:function(){if(!this.element.data("draggable"))return;return this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy(),this},_mouseCapture:function(b){var c=this.options;return this.helper||c.disabled||a(b.target).is(".ui-resizable-handle")?!1:(this.handle=this._getHandle(b),this.handle?(c.iframeFix&&a(c.iframeFix===!0?"iframe":c.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(a(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(b){var c=this.options;return this.helper=this._createHelper(b),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),a.ui.ddmanager&&(a.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,c.cursorAt&&this._adjustOffsetFromHelper(c.cursorAt),c.containment&&this._setContainment(),this._trigger("start",b)===!1?(this._clear(),!1):(this._cacheHelperProportions(),a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this._mouseDrag(b,!0),a.ui.ddmanager&&a.ui.ddmanager.dragStart(this,b),!0)},_mouseDrag:function(b,c){this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute");if(!c){var d=this._uiHash();if(this._trigger("drag",b,d)===!1)return this._mouseUp({}),!1;this.position=d.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";return a.ui.ddmanager&&a.ui.ddmanager.drag(this,b),!1},_mouseStop:function(b){var c=!1;a.ui.ddmanager&&!this.options.dropBehaviour&&(c=a.ui.ddmanager.drop(this,b)),this.dropped&&(c=this.dropped,this.dropped=!1);var d=this.element[0],e=!1;while(d&&(d=d.parentNode))d==document&&(e=!0);if(!e&&this.options.helper==="original")return!1;if(this.options.revert=="invalid"&&!c||this.options.revert=="valid"&&c||this.options.revert===!0||a.isFunction(this.options.revert)&&this.options.revert.call(this.element,c)){var f=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){f._trigger("stop",b)!==!1&&f._clear()})}else this._trigger("stop",b)!==!1&&this._clear();return!1},_mouseUp:function(b){return this.options.iframeFix===!0&&a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),a.ui.ddmanager&&a.ui.ddmanager.dragStop(this,b),a.ui.mouse.prototype._mouseUp.call(this,b)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(b){var c=!this.options.handle||!a(this.options.handle,this.element).length?!0:!1;return a(this.options.handle,this.element).find("*").andSelf().each(function(){this==b.target&&(c=!0)}),c},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b])):c.helper=="clone"?this.element.clone().removeAttr("id"):this.element;return d.parents("body").length||d.appendTo(c.appendTo=="parent"?this.element[0].parentNode:c.appendTo),d[0]!=this.element[0]&&!/(fixed|absolute)/.test(d.css("position"))&&d.css("position","absolute"),d},_adjustOffsetFromHelper:function(b){typeof b=="string"&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)b={top:0,left:0};return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var b=this.options;b.containment=="parent"&&(b.containment=this.helper[0].parentNode);if(b.containment=="document"||b.containment=="window")this.containment=[b.containment=="document"?0:a(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,b.containment=="document"?0:a(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(b.containment=="document"?0:a(window).scrollLeft())+a(b.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(b.containment=="document"?0:a(window).scrollTop())+(a(b.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(b.containment)&&b.containment.constructor!=Array){var c=a(b.containment),d=c[0];if(!d)return;var e=c.offset(),f=a(d).css("overflow")!="hidden";this.containment=[(parseInt(a(d).css("borderLeftWidth"),10)||0)+(parseInt(a(d).css("paddingLeft"),10)||0),(parseInt(a(d).css("borderTopWidth"),10)||0)+(parseInt(a(d).css("paddingTop"),10)||0),(f?Math.max(d.scrollWidth,d.offsetWidth):d.offsetWidth)-(parseInt(a(d).css("borderLeftWidth"),10)||0)-(parseInt(a(d).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(f?Math.max(d.scrollHeight,d.offsetHeight):d.offsetHeight)-(parseInt(a(d).css("borderTopWidth"),10)||0)-(parseInt(a(d).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=c}else b.containment.constructor==Array&&(this.containment=b.containment)},_convertPositionTo:function(b,c){c||(c=this.position);var d=b=="absolute"?1:-1,e=this.options,f=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=/(html|body)/i.test(f[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():g?0:f.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:f.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(d[0].tagName),f=b.pageX,g=b.pageY;if(this.originalPosition){var h;if(this.containment){if(this.relative_container){var i=this.relative_container.offset();h=[this.containment[0]+i.left,this.containment[1]+i.top,this.containment[2]+i.left,this.containment[3]+i.top]}else h=this.containment;b.pageX-this.offset.click.left<h[0]&&(f=h[0]+this.offset.click.left),b.pageY-this.offset.click.top<h[1]&&(g=h[1]+this.offset.click.top),b.pageX-this.offset.click.left>h[2]&&(f=h[2]+this.offset.click.left),b.pageY-this.offset.click.top>h[3]&&(g=h[3]+this.offset.click.top)}if(c.grid){var j=c.grid[1]?this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1]:this.originalPageY;g=h?j-this.offset.click.top<h[1]||j-this.offset.click.top>h[3]?j-this.offset.click.top<h[1]?j+c.grid[1]:j-c.grid[1]:j:j;var k=c.grid[0]?this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0]:this.originalPageX;f=h?k-this.offset.click.left<h[0]||k-this.offset.click.left>h[2]?k-this.offset.click.left<h[0]?k+c.grid[0]:k-c.grid[0]:k:k}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:d.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:d.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(b,c,d){return d=d||this._uiHash(),a.ui.plugin.call(this,b,[c,d]),b=="drag"&&(this.positionAbs=this._convertPositionTo("absolute")),a.Widget.prototype._trigger.call(this,b,c,d)},plugins:{},_uiHash:function(a){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),a.extend(a.ui.draggable,{version:"1.8.21"}),a.ui.plugin.add("draggable","connectToSortable",{start:function(b,c){var d=a(this).data("draggable"),e=d.options,f=a.extend({},c,{item:d.element});d.sortables=[],a(e.connectToSortable).each(function(){var c=a.data(this,"sortable");c&&!c.options.disabled&&(d.sortables.push({instance:c,shouldRevert:c.options.revert}),c.refreshPositions(),c._trigger("activate",b,f))})},stop:function(b,c){var d=a(this).data("draggable"),e=a.extend({},c,{item:d.element});a.each(d.sortables,function(){this.instance.isOver?(this.instance.isOver=0,d.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(b),this.instance.options.helper=this.instance.options._helper,d.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",b,e))})},drag:function(b,c){var d=a(this).data("draggable"),e=this,f=function(b){var c=this.offset.click.top,d=this.offset.click.left,e=this.positionAbs.top,f=this.positionAbs.left,g=b.height,h=b.width,i=b.top,j=b.left;return a.ui.isOver(e+c,f+d,i,j,g,h)};a.each(d.sortables,function(f){this.instance.positionAbs=d.positionAbs,this.instance.helperProportions=d.helperProportions,this.instance.offset.click=d.offset.click,this.instance._intersectsWith(this.instance.containerCache)?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=a(e).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return c.helper[0]},b.target=this.instance.currentItem[0],this.instance._mouseCapture(b,!0),this.instance._mouseStart(b,!0,!0),this.instance.offset.click.top=d.offset.click.top,this.instance.offset.click.left=d.offset.click.left,this.instance.offset.parent.left-=d.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=d.offset.parent.top-this.instance.offset.parent.top,d._trigger("toSortable",b),d.dropped=this.instance.element,d.currentItem=d.element,this.instance.fromOutside=d),this.instance.currentItem&&this.instance._mouseDrag(b)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",b,this.instance._uiHash(this.instance)),this.instance._mouseStop(b,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),d._trigger("fromSortable",b),d.dropped=!1)})}}),a.ui.plugin.add("draggable","cursor",{start:function(b,c){var d=a("body"),e=a(this).data("draggable").options;d.css("cursor")&&(e._cursor=d.css("cursor")),d.css("cursor",e.cursor)},stop:function(b,c){var d=a(this).data("draggable").options;d._cursor&&a("body").css("cursor",d._cursor)}}),a.ui.plugin.add("draggable","opacity",{start:function(b,c){var d=a(c.helper),e=a(this).data("draggable").options;d.css("opacity")&&(e._opacity=d.css("opacity")),d.css("opacity",e.opacity)},stop:function(b,c){var d=a(this).data("draggable").options;d._opacity&&a(c.helper).css("opacity",d._opacity)}}),a.ui.plugin.add("draggable","scroll",{start:function(b,c){var d=a(this).data("draggable");d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"&&(d.overflowOffset=d.scrollParent.offset())},drag:function(b,c){var d=a(this).data("draggable"),e=d.options,f=!1;if(d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"){if(!e.axis||e.axis!="x")d.overflowOffset.top+d.scrollParent[0].offsetHeight-b.pageY<e.scrollSensitivity?d.scrollParent[0].scrollTop=f=d.scrollParent[0].scrollTop+e.scrollSpeed:b.pageY-d.overflowOffset.top<e.scrollSensitivity&&(d.scrollParent[0].scrollTop=f=d.scrollParent[0].scrollTop-e.scrollSpeed);if(!e.axis||e.axis!="y")d.overflowOffset.left+d.scrollParent[0].offsetWidth-b.pageX<e.scrollSensitivity?d.scrollParent[0].scrollLeft=f=d.scrollParent[0].scrollLeft+e.scrollSpeed:b.pageX-d.overflowOffset.left<e.scrollSensitivity&&(d.scrollParent[0].scrollLeft=f=d.scrollParent[0].scrollLeft-e.scrollSpeed)}else{if(!e.axis||e.axis!="x")b.pageY-a(document).scrollTop()<e.scrollSensitivity?f=a(document).scrollTop(a(document).scrollTop()-e.scrollSpeed):a(window).height()-(b.pageY-a(document).scrollTop())<e.scrollSensitivity&&(f=a(document).scrollTop(a(document).scrollTop()+e.scrollSpeed));if(!e.axis||e.axis!="y")b.pageX-a(document).scrollLeft()<e.scrollSensitivity?f=a(document).scrollLeft(a(document).scrollLeft()-e.scrollSpeed):a(window).width()-(b.pageX-a(document).scrollLeft())<e.scrollSensitivity&&(f=a(document).scrollLeft(a(document).scrollLeft()+e.scrollSpeed))}f!==!1&&a.ui.ddmanager&&!e.dropBehaviour&&a.ui.ddmanager.prepareOffsets(d,b)}}),a.ui.plugin.add("draggable","snap",{start:function(b,c){var d=a(this).data("draggable"),e=d.options;d.snapElements=[],a(e.snap.constructor!=String?e.snap.items||":data(draggable)":e.snap).each(function(){var b=a(this),c=b.offset();this!=d.element[0]&&d.snapElements.push({item:this,width:b.outerWidth(),height:b.outerHeight(),top:c.top,left:c.left})})},drag:function(b,c){var d=a(this).data("draggable"),e=d.options,f=e.snapTolerance,g=c.offset.left,h=g+d.helperProportions.width,i=c.offset.top,j=i+d.helperProportions.height;for(var k=d.snapElements.length-1;k>=0;k--){var l=d.snapElements[k].left,m=l+d.snapElements[k].width,n=d.snapElements[k].top,o=n+d.snapElements[k].height;if(!(l-f<g&&g<m+f&&n-f<i&&i<o+f||l-f<g&&g<m+f&&n-f<j&&j<o+f||l-f<h&&h<m+f&&n-f<i&&i<o+f||l-f<h&&h<m+f&&n-f<j&&j<o+f)){d.snapElements[k].snapping&&d.options.snap.release&&d.options.snap.release.call(d.element,b,a.extend(d._uiHash(),{snapItem:d.snapElements[k].item})),d.snapElements[k].snapping=!1;continue}if(e.snapMode!="inner"){var p=Math.abs(n-j)<=f,q=Math.abs(o-i)<=f,r=Math.abs(l-h)<=f,s=Math.abs(m-g)<=f;p&&(c.position.top=d._convertPositionTo("relative",{top:n-d.helperProportions.height,left:0}).top-d.margins.top),q&&(c.position.top=d._convertPositionTo("relative",{top:o,left:0}).top-d.margins.top),r&&(c.position.left=d._convertPositionTo("relative",{top:0,left:l-d.helperProportions.width}).left-d.margins.left),s&&(c.position.left=d._convertPositionTo("relative",{top:0,left:m}).left-d.margins.left)}var t=p||q||r||s;if(e.snapMode!="outer"){var p=Math.abs(n-i)<=f,q=Math.abs(o-j)<=f,r=Math.abs(l-g)<=f,s=Math.abs(m-h)<=f;p&&(c.position.top=d._convertPositionTo("relative",{top:n,left:0}).top-d.margins.top),q&&(c.position.top=d._convertPositionTo("relative",{top:o-d.helperProportions.height,left:0}).top-d.margins.top),r&&(c.position.left=d._convertPositionTo("relative",{top:0,left:l}).left-d.margins.left),s&&(c.position.left=d._convertPositionTo("relative",{top:0,left:m-d.helperProportions.width}).left-d.margins.left)}!d.snapElements[k].snapping&&(p||q||r||s||t)&&d.options.snap.snap&&d.options.snap.snap.call(d.element,b,a.extend(d._uiHash(),{snapItem:d.snapElements[k].item})),d.snapElements[k].snapping=p||q||r||s||t}}}),a.ui.plugin.add("draggable","stack",{start:function(b,c){var d=a(this).data("draggable").options,e=a.makeArray(a(d.stack)).sort(function(b,c){return(parseInt(a(b).css("zIndex"),10)||0)-(parseInt(a(c).css("zIndex"),10)||0)});if(!e.length)return;var f=parseInt(e[0].style.zIndex)||0;a(e).each(function(a){this.style.zIndex=f+a}),this[0].style.zIndex=f+e.length}}),a.ui.plugin.add("draggable","zIndex",{start:function(b,c){var d=a(c.helper),e=a(this).data("draggable").options;d.css("zIndex")&&(e._zIndex=d.css("zIndex")),d.css("zIndex",e.zIndex)},stop:function(b,c){var d=a(this).data("draggable").options;d._zIndex&&a(c.helper).css("zIndex",d._zIndex)}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1521 * https://github.com/jquery/jquery-ui
1522 * Includes: jquery.ui.droppable.js
1523 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1524 (function(a,b){a.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect"},_create:function(){var b=this.options,c=b.accept;this.isover=0,this.isout=1,this.accept=a.isFunction(c)?c:function(a){return a.is(c)},this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight},a.ui.ddmanager.droppables[b.scope]=a.ui.ddmanager.droppables[b.scope]||[],a.ui.ddmanager.droppables[b.scope].push(this),b.addClasses&&this.element.addClass("ui-droppable")},destroy:function(){var b=a.ui.ddmanager.droppables[this.options.scope];for(var c=0;c<b.length;c++)b[c]==this&&b.splice(c,1);return this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable"),this},_setOption:function(b,c){b=="accept"&&(this.accept=a.isFunction(c)?c:function(a){return a.is(c)}),a.Widget.prototype._setOption.apply(this,arguments)},_activate:function(b){var c=a.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),c&&this._trigger("activate",b,this.ui(c))},_deactivate:function(b){var c=a.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),c&&this._trigger("deactivate",b,this.ui(c))},_over:function(b){var c=a.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0])return;this.accept.call(this.element[0],c.currentItem||c.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",b,this.ui(c)))},_out:function(b){var c=a.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0])return;this.accept.call(this.element[0],c.currentItem||c.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",b,this.ui(c)))},_drop:function(b,c){var d=c||a.ui.ddmanager.current;if(!d||(d.currentItem||d.element)[0]==this.element[0])return!1;var e=!1;return this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var b=a.data(this,"droppable");if(b.options.greedy&&!b.options.disabled&&b.options.scope==d.options.scope&&b.accept.call(b.element[0],d.currentItem||d.element)&&a.ui.intersect(d,a.extend(b,{offset:b.element.offset()}),b.options.tolerance))return e=!0,!1}),e?!1:this.accept.call(this.element[0],d.currentItem||d.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",b,this.ui(d)),this.element):!1},ui:function(a){return{draggable:a.currentItem||a.element,helper:a.helper,position:a.position,offset:a.positionAbs}}}),a.extend(a.ui.droppable,{version:"1.8.21"}),a.ui.intersect=function(b,c,d){if(!c.offset)return!1;var e=(b.positionAbs||b.position.absolute).left,f=e+b.helperProportions.width,g=(b.positionAbs||b.position.absolute).top,h=g+b.helperProportions.height,i=c.offset.left,j=i+c.proportions.width,k=c.offset.top,l=k+c.proportions.height;switch(d){case"fit":return i<=e&&f<=j&&k<=g&&h<=l;case"intersect":return i<e+b.helperProportions.width/2&&f-b.helperProportions.width/2<j&&k<g+b.helperProportions.height/2&&h-b.helperProportions.height/2<l;case"pointer":var m=(b.positionAbs||b.position.absolute).left+(b.clickOffset||b.offset.click).left,n=(b.positionAbs||b.position.absolute).top+(b.clickOffset||b.offset.click).top,o=a.ui.isOver(n,m,k,i,c.proportions.height,c.proportions.width);return o;case"touch":return(g>=k&&g<=l||h>=k&&h<=l||g<k&&h>l)&&(e>=i&&e<=j||f>=i&&f<=j||e<i&&f>j);default:return!1}},a.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(b,c){var d=a.ui.ddmanager.droppables[b.options.scope]||[],e=c?c.type:null,f=(b.currentItem||b.element).find(":data(droppable)").andSelf();g:for(var h=0;h<d.length;h++){if(d[h].options.disabled||b&&!d[h].accept.call(d[h].element[0],b.currentItem||b.element))continue;for(var i=0;i<f.length;i++)if(f[i]==d[h].element[0]){d[h].proportions.height=0;continue g}d[h].visible=d[h].element.css("display")!="none";if(!d[h].visible)continue;e=="mousedown"&&d[h]._activate.call(d[h],c),d[h].offset=d[h].element.offset(),d[h].proportions={width:d[h].element[0].offsetWidth,height:d[h].element[0].offsetHeight}}},drop:function(b,c){var d=!1;return a.each(a.ui.ddmanager.droppables[b.options.scope]||[],function(){if(!this.options)return;!this.options.disabled&&this.visible&&a.ui.intersect(b,this,this.options.tolerance)&&(d=this._drop.call(this,c)||d),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],b.currentItem||b.element)&&(this.isout=1,this.isover=0,this._deactivate.call(this,c))}),d},dragStart:function(b,c){b.element.parents(":not(body,html)").bind("scroll.droppable",function(){b.options.refreshPositions||a.ui.ddmanager.prepareOffsets(b,c)})},drag:function(b,c){b.options.refreshPositions&&a.ui.ddmanager.prepareOffsets(b,c),a.each(a.ui.ddmanager.droppables[b.options.scope]||[],function(){if(this.options.disabled||this.greedyChild||!this.visible)return;var d=a.ui.intersect(b,this,this.options.tolerance),e=!d&&this.isover==1?"isout":d&&this.isover==0?"isover":null;if(!e)return;var f;if(this.options.greedy){var g=this.element.parents(":data(droppable):eq(0)");g.length&&(f=a.data(g[0],"droppable"),f.greedyChild=e=="isover"?1:0)}f&&e=="isover"&&(f.isover=0,f.isout=1,f._out.call(f,c)),this[e]=1,this[e=="isout"?"isover":"isout"]=0,this[e=="isover"?"_over":"_out"].call(this,c),f&&e=="isout"&&(f.isout=0,f.isover=1,f._over.call(f,c))})},dragStop:function(b,c){b.element.parents(":not(body,html)").unbind("scroll.droppable"),b.options.refreshPositions||a.ui.ddmanager.prepareOffsets(b,c)}}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1525 * https://github.com/jquery/jquery-ui
1526 * Includes: jquery.ui.resizable.js
1527 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1528 (function(a,b){a.widget("ui.resizable",a.ui.mouse,{widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1e3},_create:function(){var b=this,c=this.options;this.element.addClass("ui-resizable"),a.extend(this,{_aspectRatio:!!c.aspectRatio,aspectRatio:c.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:c.helper||c.ghost||c.animate?c.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(a('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("resizable",this.element.data("resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=c.handles||(a(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se");if(this.handles.constructor==String){this.handles=="all"&&(this.handles="n,e,s,w,se,sw,ne,nw");var d=this.handles.split(",");this.handles={};for(var e=0;e<d.length;e++){var f=a.trim(d[e]),g="ui-resizable-"+f,h=a('<div class="ui-resizable-handle '+g+'"></div>');h.css({zIndex:c.zIndex}),"se"==f&&h.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[f]=".ui-resizable-"+f,this.element.append(h)}}this._renderAxis=function(b){b=b||this.element;for(var c in this.handles){this.handles[c].constructor==String&&(this.handles[c]=a(this.handles[c],this.element).show());if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var d=a(this.handles[c],this.element),e=0;e=/sw|ne|nw|se|n|s/.test(c)?d.outerHeight():d.outerWidth();var f=["padding",/ne|nw|n/.test(c)?"Top":/se|sw|s/.test(c)?"Bottom":/^e$/.test(c)?"Right":"Left"].join("");b.css(f,e),this._proportionallyResize()}if(!a(this.handles[c]).length)continue}},this._renderAxis(this.element),this._handles=a(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){if(!b.resizing){if(this.className)var a=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);b.axis=a&&a[1]?a[1]:"se"}}),c.autoHide&&(this._handles.hide(),a(this.element).addClass("ui-resizable-autohide").hover(function(){if(c.disabled)return;a(this).removeClass("ui-resizable-autohide"),b._handles.show()},function(){if(c.disabled)return;b.resizing||(a(this).addClass("ui-resizable-autohide"),b._handles.hide())})),this._mouseInit()},destroy:function(){this._mouseDestroy();var b=function(b){a(b).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){b(this.element);var c=this.element;c.after(this.originalElement.css({position:c.css("position"),width:c.outerWidth(),height:c.outerHeight(),top:c.css("top"),left:c.css("left")})).remove()}return this.originalElement.css("resize",this.originalResizeStyle),b(this.originalElement),this},_mouseCapture:function(b){var c=!1;for(var d in this.handles)a(this.handles[d])[0]==b.target&&(c=!0);return!this.options.disabled&&c},_mouseStart:function(b){var d=this.options,e=this.element.position(),f=this.element;this.resizing=!0,this.documentScroll={top:a(document).scrollTop(),left:a(document).scrollLeft()},(f.is(".ui-draggable")||/absolute/.test(f.css("position")))&&f.css({position:"absolute",top:e.top,left:e.left}),this._renderProxy();var g=c(this.helper.css("left")),h=c(this.helper.css("top"));d.containment&&(g+=a(d.containment).scrollLeft()||0,h+=a(d.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:g,top:h},this.size=this._helper?{width:f.outerWidth(),height:f.outerHeight()}:{width:f.width(),height:f.height()},this.originalSize=this._helper?{width:f.outerWidth(),height:f.outerHeight()}:{width:f.width(),height:f.height()},this.originalPosition={left:g,top:h},this.sizeDiff={width:f.outerWidth()-f.width(),height:f.outerHeight()-f.height()},this.originalMousePosition={left:b.pageX,top:b.pageY},this.aspectRatio=typeof d.aspectRatio=="number"?d.aspectRatio:this.originalSize.width/this.originalSize.height||1;var i=a(".ui-resizable-"+this.axis).css("cursor");return a("body").css("cursor",i=="auto"?this.axis+"-resize":i),f.addClass("ui-resizable-resizing"),this._propagate("start",b),!0},_mouseDrag:function(b){var c=this.helper,d=this.options,e={},f=this,g=this.originalMousePosition,h=this.axis,i=b.pageX-g.left||0,j=b.pageY-g.top||0,k=this._change[h];if(!k)return!1;var l=k.apply(this,[b,i,j]),m=a.browser.msie&&a.browser.version<7,n=this.sizeDiff;this._updateVirtualBoundaries(b.shiftKey);if(this._aspectRatio||b.shiftKey)l=this._updateRatio(l,b);return l=this._respectSize(l,b),this._propagate("resize",b),c.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"}),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),this._updateCache(l),this._trigger("resize",b,this.ui()),!1},_mouseStop:function(b){this.resizing=!1;var c=this.options,d=this;if(this._helper){var e=this._proportionallyResizeElements,f=e.length&&/textarea/i.test(e[0].nodeName),g=f&&a.ui.hasScroll(e[0],"left")?0:d.sizeDiff.height,h=f?0:d.sizeDiff.width,i={width:d.helper.width()-h,height:d.helper.height()-g},j=parseInt(d.element.css("left"),10)+(d.position.left-d.originalPosition.left)||null,k=parseInt(d.element.css("top"),10)+(d.position.top-d.originalPosition.top)||null;c.animate||this.element.css(a.extend(i,{top:k,left:j})),d.helper.height(d.size.height),d.helper.width(d.size.width),this._helper&&!c.animate&&this._proportionallyResize()}return a("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",b),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(a){var b=this.options,c,e,f,g,h;h={minWidth:d(b.minWidth)?b.minWidth:0,maxWidth:d(b.maxWidth)?b.maxWidth:Infinity,minHeight:d(b.minHeight)?b.minHeight:0,maxHeight:d(b.maxHeight)?b.maxHeight:Infinity};if(this._aspectRatio||a)c=h.minHeight*this.aspectRatio,f=h.minWidth/this.aspectRatio,e=h.maxHeight*this.aspectRatio,g=h.maxWidth/this.aspectRatio,c>h.minWidth&&(h.minWidth=c),f>h.minHeight&&(h.minHeight=f),e<h.maxWidth&&(h.maxWidth=e),g<h.maxHeight&&(h.maxHeight=g);this._vBoundaries=h},_updateCache:function(a){var b=this.options;this.offset=this.helper.offset(),d(a.left)&&(this.position.left=a.left),d(a.top)&&(this.position.top=a.top),d(a.height)&&(this.size.height=a.height),d(a.width)&&(this.size.width=a.width)},_updateRatio:function(a,b){var c=this.options,e=this.position,f=this.size,g=this.axis;return d(a.height)?a.width=a.height*this.aspectRatio:d(a.width)&&(a.height=a.width/this.aspectRatio),g=="sw"&&(a.left=e.left+(f.width-a.width),a.top=null),g=="nw"&&(a.top=e.top+(f.height-a.height),a.left=e.left+(f.width-a.width)),a},_respectSize:function(a,b){var c=this.helper,e=this._vBoundaries,f=this._aspectRatio||b.shiftKey,g=this.axis,h=d(a.width)&&e.maxWidth&&e.maxWidth<a.width,i=d(a.height)&&e.maxHeight&&e.maxHeight<a.height,j=d(a.width)&&e.minWidth&&e.minWidth>a.width,k=d(a.height)&&e.minHeight&&e.minHeight>a.height;j&&(a.width=e.minWidth),k&&(a.height=e.minHeight),h&&(a.width=e.maxWidth),i&&(a.height=e.maxHeight);var l=this.originalPosition.left+this.originalSize.width,m=this.position.top+this.size.height,n=/sw|nw|w/.test(g),o=/nw|ne|n/.test(g);j&&n&&(a.left=l-e.minWidth),h&&n&&(a.left=l-e.maxWidth),k&&o&&(a.top=m-e.minHeight),i&&o&&(a.top=m-e.maxHeight);var p=!a.width&&!a.height;return p&&!a.left&&a.top?a.top=null:p&&!a.top&&a.left&&(a.left=null),a},_proportionallyResize:function(){var b=this.options;if(!this._proportionallyResizeElements.length)return;var c=this.helper||this.element;for(var d=0;d<this._proportionallyResizeElements.length;d++){var e=this._proportionallyResizeElements[d];if(!this.borderDif){var f=[e.css("borderTopWidth"),e.css("borderRightWidth"),e.css("borderBottomWidth"),e.css("borderLeftWidth")],g=[e.css("paddingTop"),e.css("paddingRight"),e.css("paddingBottom"),e.css("paddingLeft")];this.borderDif=a.map(f,function(a,b){var c=parseInt(a,10)||0,d=parseInt(g[b],10)||0;return c+d})}if(!a.browser.msie||!a(c).is(":hidden")&&!a(c).parents(":hidden").length)e.css({height:c.height()-this.borderDif[0]-this.borderDif[2]||0,width:c.width()-this.borderDif[1]-this.borderDif[3]||0});else continue}},_renderProxy:function(){var b=this.element,c=this.options;this.elementOffset=b.offset();if(this._helper){this.helper=this.helper||a('<div style="overflow:hidden;"></div>');var d=a.browser.msie&&a.browser.version<7,e=d?1:0,f=d?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+f,height:this.element.outerHeight()+f,position:"absolute",left:this.elementOffset.left-e+"px",top:this.elementOffset.top-e+"px",zIndex:++c.zIndex}),this.helper.appendTo("body").disableSelection()}else this.helper=this.element},_change:{e:function(a,b,c){return{width:this.originalSize.width+b}},w:function(a,b,c){var d=this.options,e=this.originalSize,f=this.originalPosition;return{left:f.left+b,width:e.width-b}},n:function(a,b,c){var d=this.options,e=this.originalSize,f=this.originalPosition;return{top:f.top+c,height:e.height-c}},s:function(a,b,c){return{height:this.originalSize.height+c}},se:function(b,c,d){return a.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[b,c,d]))},sw:function(b,c,d){return a.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[b,c,d]))},ne:function(b,c,d){return a.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[b,c,d]))},nw:function(b,c,d){return a.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[b,c,d]))}},_propagate:function(b,c){a.ui.plugin.call(this,b,[c,this.ui()]),b!="resize"&&this._trigger(b,c,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),a.extend(a.ui.resizable,{version:"1.8.21"}),a.ui.plugin.add("resizable","alsoResize",{start:function(b,c){var d=a(this).data("resizable"),e=d.options,f=function(b){a(b).each(function(){var b=a(this);b.data("resizable-alsoresize",{width:parseInt(b.width(),10),height:parseInt(b.height(),10),left:parseInt(b.css("left"),10),top:parseInt(b.css("top"),10)})})};typeof e.alsoResize=="object"&&!e.alsoResize.parentNode?e.alsoResize.length?(e.alsoResize=e.alsoResize[0],f(e.alsoResize)):a.each(e.alsoResize,function(a){f(a)}):f(e.alsoResize)},resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.originalSize,g=d.originalPosition,h={height:d.size.height-f.height||0,width:d.size.width-f.width||0,top:d.position.top-g.top||0,left:d.position.left-g.left||0},i=function(b,d){a(b).each(function(){var b=a(this),e=a(this).data("resizable-alsoresize"),f={},g=d&&d.length?d:b.parents(c.originalElement[0]).length?["width","height"]:["width","height","top","left"];a.each(g,function(a,b){var c=(e[b]||0)+(h[b]||0);c&&c>=0&&(f[b]=c||null)}),b.css(f)})};typeof e.alsoResize=="object"&&!e.alsoResize.nodeType?a.each(e.alsoResize,function(a,b){i(a,b)}):i(e.alsoResize)},stop:function(b,c){a(this).removeData("resizable-alsoresize")}}),a.ui.plugin.add("resizable","animate",{stop:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d._proportionallyResizeElements,g=f.length&&/textarea/i.test(f[0].nodeName),h=g&&a.ui.hasScroll(f[0],"left")?0:d.sizeDiff.height,i=g?0:d.sizeDiff.width,j={width:d.size.width-i,height:d.size.height-h},k=parseInt(d.element.css("left"),10)+(d.position.left-d.originalPosition.left)||null,l=parseInt(d.element.css("top"),10)+(d.position.top-d.originalPosition.top)||null;d.element.animate(a.extend(j,l&&k?{top:l,left:k}:{}),{duration:e.animateDuration,easing:e.animateEasing,step:function(){var c={width:parseInt(d.element.css("width"),10),height:parseInt(d.element.css("height"),10),top:parseInt(d.element.css("top"),10),left:parseInt(d.element.css("left"),10)};f&&f.length&&a(f[0]).css({width:c.width,height:c.height}),d._updateCache(c),d._propagate("resize",b)}})}}),a.ui.plugin.add("resizable","containment",{start:function(b,d){var e=a(this).data("resizable"),f=e.options,g=e.element,h=f.containment,i=h instanceof a?h.get(0):/parent/.test(h)?g.parent().get(0):h;if(!i)return;e.containerElement=a(i);if(/document/.test(h)||h==document)e.containerOffset={left:0,top:0},e.containerPosition={left:0,top:0},e.parentData={element:a(document),left:0,top:0,width:a(document).width(),height:a(document).height()||document.body.parentNode.scrollHeight};else{var j=a(i),k=[];a(["Top","Right","Left","Bottom"]).each(function(a,b){k[a]=c(j.css("padding"+b))}),e.containerOffset=j.offset(),e.containerPosition=j.position(),e.containerSize={height:j.innerHeight()-k[3],width:j.innerWidth()-k[1]};var l=e.containerOffset,m=e.containerSize.height,n=e.containerSize.width,o=a.ui.hasScroll(i,"left")?i.scrollWidth:n,p=a.ui.hasScroll(i)?i.scrollHeight:m;e.parentData={element:i,left:l.left,top:l.top,width:o,height:p}}},resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.containerSize,g=d.containerOffset,h=d.size,i=d.position,j=d._aspectRatio||b.shiftKey,k={top:0,left:0},l=d.containerElement;l[0]!=document&&/static/.test(l.css("position"))&&(k=g),i.left<(d._helper?g.left:0)&&(d.size.width=d.size.width+(d._helper?d.position.left-g.left:d.position.left-k.left),j&&(d.size.height=d.size.width/d.aspectRatio),d.position.left=e.helper?g.left:0),i.top<(d._helper?g.top:0)&&(d.size.height=d.size.height+(d._helper?d.position.top-g.top:d.position.top),j&&(d.size.width=d.size.height*d.aspectRatio),d.position.top=d._helper?g.top:0),d.offset.left=d.parentData.left+d.position.left,d.offset.top=d.parentData.top+d.position.top;var m=Math.abs((d._helper?d.offset.left-k.left:d.offset.left-k.left)+d.sizeDiff.width),n=Math.abs((d._helper?d.offset.top-k.top:d.offset.top-g.top)+d.sizeDiff.height),o=d.containerElement.get(0)==d.element.parent().get(0),p=/relative|absolute/.test(d.containerElement.css("position"));o&&p&&(m-=d.parentData.left),m+d.size.width>=d.parentData.width&&(d.size.width=d.parentData.width-m,j&&(d.size.height=d.size.width/d.aspectRatio)),n+d.size.height>=d.parentData.height&&(d.size.height=d.parentData.height-n,j&&(d.size.width=d.size.height*d.aspectRatio))},stop:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.position,g=d.containerOffset,h=d.containerPosition,i=d.containerElement,j=a(d.helper),k=j.offset(),l=j.outerWidth()-d.sizeDiff.width,m=j.outerHeight()-d.sizeDiff.height;d._helper&&!e.animate&&/relative/.test(i.css("position"))&&a(this).css({left:k.left-h.left-g.left,width:l,height:m}),d._helper&&!e.animate&&/static/.test(i.css("position"))&&a(this).css({left:k.left-h.left-g.left,width:l,height:m})}}),a.ui.plugin.add("resizable","ghost",{start:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.size;d.ghost=d.originalElement.clone(),d.ghost.css({opacity:.25,display:"block",position:"relative",height:f.height,width:f.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof e.ghost=="string"?e.ghost:""),d.ghost.appendTo(d.helper)},resize:function(b,c){var d=a(this).data("resizable"),e=d.options;d.ghost&&d.ghost.css({position:"relative",height:d.size.height,width:d.size.width})},stop:function(b,c){var d=a(this).data("resizable"),e=d.options;d.ghost&&d.helper&&d.helper.get(0).removeChild(d.ghost.get(0))}}),a.ui.plugin.add("resizable","grid",{resize:function(b,c){var d=a(this).data("resizable"),e=d.options,f=d.size,g=d.originalSize,h=d.originalPosition,i=d.axis,j=e._aspectRatio||b.shiftKey;e.grid=typeof e.grid=="number"?[e.grid,e.grid]:e.grid;var k=Math.round((f.width-g.width)/(e.grid[0]||1))*(e.grid[0]||1),l=Math.round((f.height-g.height)/(e.grid[1]||1))*(e.grid[1]||1);/^(se|s|e)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l):/^(ne)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l,d.position.top=h.top-l):/^(sw)$/.test(i)?(d.size.width=g.width+k,d.size.height=g.height+l,d.position.left=h.left-k):(d.size.width=g.width+k,d.size.height=g.height+l,d.position.top=h.top-l,d.position.left=h.left-k)}});var c=function(a){return parseInt(a,10)||0},d=function(a){return!isNaN(parseInt(a,10))}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1529 * https://github.com/jquery/jquery-ui
1530 * Includes: jquery.ui.selectable.js
1531 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1532 (function(a,b){a.widget("ui.selectable",a.ui.mouse,{options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch"},_create:function(){var b=this;this.element.addClass("ui-selectable"),this.dragged=!1;var c;this.refresh=function(){c=a(b.options.filter,b.element[0]),c.addClass("ui-selectee"),c.each(function(){var b=a(this),c=b.offset();a.data(this,"selectable-item",{element:this,$element:b,left:c.left,top:c.top,right:c.left+b.outerWidth(),bottom:c.top+b.outerHeight(),startselected:!1,selected:b.hasClass("ui-selected"),selecting:b.hasClass("ui-selecting"),unselecting:b.hasClass("ui-unselecting")})})},this.refresh(),this.selectees=c.addClass("ui-selectee"),this._mouseInit(),this.helper=a("<div class='ui-selectable-helper'></div>")},destroy:function(){return this.selectees.removeClass("ui-selectee").removeData("selectable-item"),this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable"),this._mouseDestroy(),this},_mouseStart:function(b){var c=this;this.opos=[b.pageX,b.pageY];if(this.options.disabled)return;var d=this.options;this.selectees=a(d.filter,this.element[0]),this._trigger("start",b),a(d.appendTo).append(this.helper),this.helper.css({left:b.clientX,top:b.clientY,width:0,height:0}),d.autoRefresh&&this.refresh(),this.selectees.filter(".ui-selected").each(function(){var d=a.data(this,"selectable-item");d.startselected=!0,!b.metaKey&&!b.ctrlKey&&(d.$element.removeClass("ui-selected"),d.selected=!1,d.$element.addClass("ui-unselecting"),d.unselecting=!0,c._trigger("unselecting",b,{unselecting:d.element}))}),a(b.target).parents().andSelf().each(function(){var d=a.data(this,"selectable-item");if(d){var e=!b.metaKey&&!b.ctrlKey||!d.$element.hasClass("ui-selected");return d.$element.removeClass(e?"ui-unselecting":"ui-selected").addClass(e?"ui-selecting":"ui-unselecting"),d.unselecting=!e,d.selecting=e,d.selected=e,e?c._trigger("selecting",b,{selecting:d.element}):c._trigger("unselecting",b,{unselecting:d.element}),!1}})},_mouseDrag:function(b){var c=this;this.dragged=!0;if(this.options.disabled)return;var d=this.options,e=this.opos[0],f=this.opos[1],g=b.pageX,h=b.pageY;if(e>g){var i=g;g=e,e=i}if(f>h){var i=h;h=f,f=i}return this.helper.css({left:e,top:f,width:g-e,height:h-f}),this.selectees.each(function(){var i=a.data(this,"selectable-item");if(!i||i.element==c.element[0])return;var j=!1;d.tolerance=="touch"?j=!(i.left>g||i.right<e||i.top>h||i.bottom<f):d.tolerance=="fit"&&(j=i.left>e&&i.right<g&&i.top>f&&i.bottom<h),j?(i.selected&&(i.$element.removeClass("ui-selected"),i.selected=!1),i.unselecting&&(i.$element.removeClass("ui-unselecting"),i.unselecting=!1),i.selecting||(i.$element.addClass("ui-selecting"),i.selecting=!0,c._trigger("selecting",b,{selecting:i.element}))):(i.selecting&&((b.metaKey||b.ctrlKey)&&i.startselected?(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.$element.addClass("ui-selected"),i.selected=!0):(i.$element.removeClass("ui-selecting"),i.selecting=!1,i.startselected&&(i.$element.addClass("ui-unselecting"),i.unselecting=!0),c._trigger("unselecting",b,{unselecting:i.element}))),i.selected&&!b.metaKey&&!b.ctrlKey&&!i.startselected&&(i.$element.removeClass("ui-selected"),i.selected=!1,i.$element.addClass("ui-unselecting"),i.unselecting=!0,c._trigger("unselecting",b,{unselecting:i.element})))}),!1},_mouseStop:function(b){var c=this;this.dragged=!1;var d=this.options;return a(".ui-unselecting",this.element[0]).each(function(){var d=a.data(this,"selectable-item");d.$element.removeClass("ui-unselecting"),d.unselecting=!1,d.startselected=!1,c._trigger("unselected",b,{unselected:d.element})}),a(".ui-selecting",this.element[0]).each(function(){var d=a.data(this,"selectable-item");d.$element.removeClass("ui-selecting").addClass("ui-selected"),d.selecting=!1,d.selected=!0,d.startselected=!0,c._trigger("selected",b,{selected:d.element})}),this._trigger("stop",b),this.helper.remove(),!1}}),a.extend(a.ui.selectable,{version:"1.8.21"})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1533 * https://github.com/jquery/jquery-ui
1534 * Includes: jquery.ui.sortable.js
1535 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1536 (function(a,b){a.widget("ui.sortable",a.ui.mouse,{widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3},_create:function(){var a=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?a.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},destroy:function(){a.Widget.prototype.destroy.call(this),this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var b=this.items.length-1;b>=0;b--)this.items[b].item.removeData(this.widgetName+"-item");return this},_setOption:function(b,c){b==="disabled"?(this.options[b]=c,this.widget()[c?"addClass":"removeClass"]("ui-sortable-disabled")):a.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(b,c){var d=this;if(this.reverting)return!1;if(this.options.disabled||this.options.type=="static")return!1;this._refreshItems(b);var e=null,f=this,g=a(b.target).parents().each(function(){if(a.data(this,d.widgetName+"-item")==f)return e=a(this),!1});a.data(b.target,d.widgetName+"-item")==f&&(e=a(b.target));if(!e)return!1;if(this.options.handle&&!c){var h=!1;a(this.options.handle,e).find("*").andSelf().each(function(){this==b.target&&(h=!0)});if(!h)return!1}return this.currentItem=e,this._removeCurrentsFromItems(),!0},_mouseStart:function(b,c,d){var e=this.options,f=this;this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(b),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(b),this.originalPageX=b.pageX,this.originalPageY=b.pageY,e.cursorAt&&this._adjustOffsetFromHelper(e.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!=this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),e.containment&&this._setContainment(),e.cursor&&(a("body").css("cursor")&&(this._storedCursor=a("body").css("cursor")),a("body").css("cursor",e.cursor)),e.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",e.opacity)),e.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",e.zIndex)),this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",b,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions();if(!d)for(var g=this.containers.length-1;g>=0;g--)this.containers[g]._trigger("activate",b,f._uiHash(this));return a.ui.ddmanager&&(a.ui.ddmanager.current=this),a.ui.ddmanager&&!e.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(b),!0},_mouseDrag:function(b){this.position=this._generatePosition(b),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs);if(this.options.scroll){var c=this.options,d=!1;this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-b.pageY<c.scrollSensitivity?this.scrollParent[0].scrollTop=d=this.scrollParent[0].scrollTop+c.scrollSpeed:b.pageY-this.overflowOffset.top<c.scrollSensitivity&&(this.scrollParent[0].scrollTop=d=this.scrollParent[0].scrollTop-c.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-b.pageX<c.scrollSensitivity?this.scrollParent[0].scrollLeft=d=this.scrollParent[0].scrollLeft+c.scrollSpeed:b.pageX-this.overflowOffset.left<c.scrollSensitivity&&(this.scrollParent[0].scrollLeft=d=this.scrollParent[0].scrollLeft-c.scrollSpeed)):(b.pageY-a(document).scrollTop()<c.scrollSensitivity?d=a(document).scrollTop(a(document).scrollTop()-c.scrollSpeed):a(window).height()-(b.pageY-a(document).scrollTop())<c.scrollSensitivity&&(d=a(document).scrollTop(a(document).scrollTop()+c.scrollSpeed)),b.pageX-a(document).scrollLeft()<c.scrollSensitivity?d=a(document).scrollLeft(a(document).scrollLeft()-c.scrollSpeed):a(window).width()-(b.pageX-a(document).scrollLeft())<c.scrollSensitivity&&(d=a(document).scrollLeft(a(document).scrollLeft()+c.scrollSpeed))),d!==!1&&a.ui.ddmanager&&!c.dropBehaviour&&a.ui.ddmanager.prepareOffsets(this,b)}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(var e=this.items.length-1;e>=0;e--){var f=this.items[e],g=f.item[0],h=this._intersectsWithPointer(f);if(!h)continue;if(g!=this.currentItem[0]&&this.placeholder[h==1?"next":"prev"]()[0]!=g&&!a.ui.contains(this.placeholder[0],g)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],g):!0)){this.direction=h==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(f))this._rearrange(b,f);else break;this._trigger("change",b,this._uiHash());break}}return this._contactContainers(b),a.ui.ddmanager&&a.ui.ddmanager.drag(this,b),this._trigger("sort",b,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(b,c){if(!b)return;a.ui.ddmanager&&!this.options.dropBehaviour&&a.ui.ddmanager.drop(this,b);if(this.options.revert){var d=this,e=d.placeholder.offset();d.reverting=!0,a(this.helper).animate({left:e.left-this.offset.parent.left-d.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:e.top-this.offset.parent.top-d.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){d._clear(b)})}else this._clear(b,c);return!1},cancel:function(){var b=this;if(this.dragging){this._mouseUp({target:null}),this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var c=this.containers.length-1;c>=0;c--)this.containers[c]._trigger("deactivate",null,b._uiHash(this)),this.containers[c].containerCache.over&&(this.containers[c]._trigger("out",null,b._uiHash(this)),this.containers[c].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),a.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?a(this.domPosition.prev).after(this.currentItem):a(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];return b=b||{},a(c).each(function(){var c=(a(b.item||this).attr(b.attribute||"id")||"").match(b.expression||/(.+)[-=_](.+)/);c&&d.push((b.key||c[1]+"[]")+"="+(b.key&&b.expression?c[1]:c[2]))}),!d.length&&b.key&&d.push(b.key+"="),d.join("&")},toArray:function(b){var c=this._getItemsAsjQuery(b&&b.connected),d=[];return b=b||{},c.each(function(){d.push(a(b.item||this).attr(b.attribute||"id")||"")}),d},_intersectsWith:function(a){var b=this.positionAbs.left,c=b+this.helperProportions.width,d=this.positionAbs.top,e=d+this.helperProportions.height,f=a.left,g=f+a.width,h=a.top,i=h+a.height,j=this.offset.click.top,k=this.offset.click.left,l=d+j>h&&d+j<i&&b+k>f&&b+k<g;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>a[this.floating?"width":"height"]?l:f<b+this.helperProportions.width/2&&c-this.helperProportions.width/2<g&&h<d+this.helperProportions.height/2&&e-this.helperProportions.height/2<i},_intersectsWithPointer:function(b){var c=this.options.axis==="x"||a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,b.top,b.height),d=this.options.axis==="y"||a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,b.left,b.width),e=c&&d,f=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();return e?this.floating?g&&g=="right"||f=="down"?2:1:f&&(f=="down"?2:1):!1},_intersectsWithSides:function(b){var c=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,b.top+b.height/2,b.height),d=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,b.left+b.width/2,b.width),e=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();return this.floating&&f?f=="right"&&d||f=="left"&&!d:e&&(e=="down"&&c||e=="up"&&!c)},_getDragVerticalDirection:function(){var a=this.positionAbs.top-this.lastPositionAbs.top;return a!=0&&(a>0?"down":"up")},_getDragHorizontalDirection:function(){var a=this.positionAbs.left-this.lastPositionAbs.left;return a!=0&&(a>0?"right":"left")},refresh:function(a){return this._refreshItems(a),this.refreshPositions(),this},_connectWith:function(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith},_getItemsAsjQuery:function(b){var c=this,d=[],e=[],f=this._connectWith();if(f&&b)for(var g=f.length-1;g>=0;g--){var h=a(f[g]);for(var i=h.length-1;i>=0;i--){var j=a.data(h[i],this.widgetName);j&&j!=this&&!j.options.disabled&&e.push([a.isFunction(j.options.items)?j.options.items.call(j.element):a(j.options.items,j.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),j])}}e.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var g=e.length-1;g>=0;g--)e[g][0].each(function(){d.push(this)});return a(d)},_removeCurrentsFromItems:function(){var a=this.currentItem.find(":data("+this.widgetName+"-item)");for(var b=0;b<this.items.length;b++)for(var c=0;c<a.length;c++)a[c]==this.items[b].item[0]&&this.items.splice(b,1)},_refreshItems:function(b){this.items=[],this.containers=[this];var c=this.items,d=this,e=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],b,{item:this.currentItem}):a(this.options.items,this.element),this]],f=this._connectWith();if(f&&this.ready)for(var g=f.length-1;g>=0;g--){var h=a(f[g]);for(var i=h.length-1;i>=0;i--){var j=a.data(h[i],this.widgetName);j&&j!=this&&!j.options.disabled&&(e.push([a.isFunction(j.options.items)?j.options.items.call(j.element[0],b,{item:this.currentItem}):a(j.options.items,j.element),j]),this.containers.push(j))}}for(var g=e.length-1;g>=0;g--){var k=e[g][1],l=e[g][0];for(var i=0,m=l.length;i<m;i++){var n=a(l[i]);n.data(this.widgetName+"-item",k),c.push({item:n,instance:k,width:0,height:0,left:0,top:0})}}},refreshPositions:function(b){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());for(var c=this.items.length-1;c>=0;c--){var d=this.items[c];if(d.instance!=this.currentContainer&&this.currentContainer&&d.item[0]!=this.currentItem[0])continue;var e=this.options.toleranceElement?a(this.options.toleranceElement,d.item):d.item;b||(d.width=e.outerWidth(),d.height=e.outerHeight());var f=e.offset();d.left=f.left,d.top=f.top}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(var c=this.containers.length-1;c>=0;c--){var f=this.containers[c].element.offset();this.containers[c].containerCache.left=f.left,this.containers[c].containerCache.top=f.top,this.containers[c].containerCache.width=this.containers[c].element.outerWidth(),this.containers[c].containerCache.height=this.containers[c].element.outerHeight()}return this},_createPlaceholder:function(b){var c=b||this,d=c.options;if(!d.placeholder||d.placeholder.constructor==String){var e=d.placeholder;d.placeholder={element:function(){var b=a(document.createElement(c.currentItem[0].nodeName)).addClass(e||c.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];return e||(b.style.visibility="hidden"),b},update:function(a,b){if(e&&!d.forcePlaceholderSize)return;b.height()||b.height(c.currentItem.innerHeight()-parseInt(c.currentItem.css("paddingTop")||0,10)-parseInt(c.currentItem.css("paddingBottom")||0,10)),b.width()||b.width(c.currentItem.innerWidth()-parseInt(c.currentItem.css("paddingLeft")||0,10)-parseInt(c.currentItem.css("paddingRight")||0,10))}}}c.placeholder=a(d.placeholder.element.call(c.element,c.currentItem)),c.currentItem.after(c.placeholder),d.placeholder.update(c,c.placeholder)},_contactContainers:function(b){var c=null,d=null;for(var e=this.containers.length-1;e>=0;e--){if(a.ui.contains(this.currentItem[0],this.containers[e].element[0]))continue;if(this._intersectsWith(this.containers[e].containerCache)){if(c&&a.ui.contains(this.containers[e].element[0],c.element[0]))continue;c=this.containers[e],d=e}else this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",b,this._uiHash(this)),this.containers[e].containerCache.over=0)}if(!c)return;if(this.containers.length===1)this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1;else if(this.currentContainer!=this.containers[d]){var f=1e4,g=null,h=this.positionAbs[this.containers[d].floating?"left":"top"];for(var i=this.items.length-1;i>=0;i--){if(!a.ui.contains(this.containers[d].element[0],this.items[i].item[0]))continue;var j=this.containers[d].floating?this.items[i].item.offset().left:this.items[i].item.offset().top;Math.abs(j-h)<f&&(f=Math.abs(j-h),g=this.items[i],this.direction=j-h>0?"down":"up")}if(!g&&!this.options.dropOnEmpty)return;this.currentContainer=this.containers[d],g?this._rearrange(b,g,null,!0):this._rearrange(b,null,this.containers[d].element,!0),this._trigger("change",b,this._uiHash()),this.containers[d]._trigger("change",b,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[d]._trigger("over",b,this._uiHash(this)),this.containers[d].containerCache.over=1}},_createHelper:function(b){var c=this.options,d=a.isFunction(c.helper)?a(c.helper.apply(this.element[0],[b,this.currentItem])):c.helper=="clone"?this.currentItem.clone():this.currentItem;return d.parents("body").length||a(c.appendTo!="parent"?c.appendTo:this.currentItem[0].parentNode)[0].appendChild(d[0]),d[0]==this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(d[0].style.width==""||c.forceHelperSize)&&d.width(this.currentItem.width()),(d[0].style.height==""||c.forceHelperSize)&&d.height(this.currentItem.height()),d},_adjustOffsetFromHelper:function(b){typeof b=="string"&&(b=b.split(" ")),a.isArray(b)&&(b={left:+b[0],top:+b[1]||0}),"left"in b&&(this.offset.click.left=b.left+this.margins.left),"right"in b&&(this.offset.click.left=this.helperProportions.width-b.right+this.margins.left),"top"in b&&(this.offset.click.top=b.top+this.margins.top),"bottom"in b&&(this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(b.left+=this.scrollParent.scrollLeft(),b.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)b={top:0,left:0};return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.currentItem.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var b=this.options;b.containment=="parent"&&(b.containment=this.helper[0].parentNode);if(b.containment=="document"||b.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(b.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(b.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(b.containment)){var c=a(b.containment)[0],d=a(b.containment).offset(),e=a(c).css("overflow")!="hidden";this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(e?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(e?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(b,c){c||(c=this.position);var d=b=="absolute"?1:-1,e=this.options,f=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=/(html|body)/i.test(f[0].tagName);return{top:c.top+this.offset.relative.top*d+this.offset.parent.top*d-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():g?0:f.scrollTop())*d),left:c.left+this.offset.relative.left*d+this.offset.parent.left*d-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:f.scrollLeft())*d)}},_generatePosition:function(b){var c=this.options,d=this.cssPosition=="absolute"&&(this.scrollParent[0]==document||!a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,e=/(html|body)/i.test(d[0].tagName);this.cssPosition=="relative"&&(this.scrollParent[0]==document||this.scrollParent[0]==this.offsetParent[0])&&(this.offset.relative=this._getRelativeOffset());var f=b.pageX,g=b.pageY;if(this.originalPosition){this.containment&&(b.pageX-this.offset.click.left<this.containment[0]&&(f=this.containment[0]+this.offset.click.left),b.pageY-this.offset.click.top<this.containment[1]&&(g=this.containment[1]+this.offset.click.top),b.pageX-this.offset.click.left>this.containment[2]&&(f=this.containment[2]+this.offset.click.left),b.pageY-this.offset.click.top>this.containment[3]&&(g=this.containment[3]+this.offset.click.top));if(c.grid){var h=this.originalPageY+Math.round((g-this.originalPageY)/c.grid[1])*c.grid[1];g=this.containment?h-this.offset.click.top<this.containment[1]||h-this.offset.click.top>this.containment[3]?h-this.offset.click.top<this.containment[1]?h+c.grid[1]:h-c.grid[1]:h:h;var i=this.originalPageX+Math.round((f-this.originalPageX)/c.grid[0])*c.grid[0];f=this.containment?i-this.offset.click.left<this.containment[0]||i-this.offset.click.left>this.containment[2]?i-this.offset.click.left<this.containment[0]?i+c.grid[0]:i-c.grid[0]:i:i}}return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():e?0:d.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():e?0:d.scrollLeft())}},_rearrange:function(a,b,c,d){c?c[0].appendChild(this.placeholder[0]):b.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?b.item[0]:b.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var e=this,f=this.counter;window.setTimeout(function(){f==e.counter&&e.refreshPositions(!d)},0)},_clear:function(b,c){this.reverting=!1;var d=[],e=this;!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var f in this._storedCSS)if(this._storedCSS[f]=="auto"||this._storedCSS[f]=="static")this._storedCSS[f]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!c&&d.push(function(a){this._trigger("receive",a,this._uiHash(this.fromOutside))}),(this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!c&&d.push(function(a){this._trigger("update",a,this._uiHash())});if(!a.ui.contains(this.element[0],this.currentItem[0])){c||d.push(function(a){this._trigger("remove",a,this._uiHash())});for(var f=this.containers.length-1;f>=0;f--)a.ui.contains(this.containers[f].element[0],this.currentItem[0])&&!c&&(d.push(function(a){return function(b){a._trigger("receive",b,this._uiHash(this))}}.call(this,this.containers[f])),d.push(function(a){return function(b){a._trigger("update",b,this._uiHash(this))}}.call(this,this.containers[f])))}for(var f=this.containers.length-1;f>=0;f--)c||d.push(function(a){return function(b){a._trigger("deactivate",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over&&(d.push(function(a){return function(b){a._trigger("out",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over=0);this._storedCursor&&a("body").css("cursor",this._storedCursor),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex),this.dragging=!1;if(this.cancelHelperRemoval){if(!c){this._trigger("beforeStop",b,this._uiHash());for(var f=0;f<d.length;f++)d[f].call(this,b);this._trigger("stop",b,this._uiHash())}return!1}c||this._trigger("beforeStop",b,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!=this.currentItem[0]&&this.helper.remove(),this.helper=null;if(!c){for(var f=0;f<d.length;f++)d[f].call(this,b);this._trigger("stop",b,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){a.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(b){var c=b||this;return{helper:c.helper,placeholder:c.placeholder||a([]),position:c.position,originalPosition:c.originalPosition,offset:c.positionAbs,item:c.currentItem,sender:b?b.element:null}}}),a.extend(a.ui.sortable,{version:"1.8.21"})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1537 * https://github.com/jquery/jquery-ui
1538 * Includes: jquery.ui.accordion.js
1539 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1540 (function(a,b){a.widget("ui.accordion",{options:{active:0,animated:"slide",autoHeight:!0,clearStyle:!1,collapsible:!1,event:"click",fillSpace:!1,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:!1,navigationFilter:function(){return this.href.toLowerCase()===location.href.toLowerCase()}},_create:function(){var b=this,c=b.options;b.running=0,b.element.addClass("ui-accordion ui-widget ui-helper-reset").children("li").addClass("ui-accordion-li-fix"),b.headers=b.element.find(c.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){if(c.disabled)return;a(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){if(c.disabled)return;a(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){if(c.disabled)return;a(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){if(c.disabled)return;a(this).removeClass("ui-state-focus")}),b.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");if(c.navigation){var d=b.element.find("a").filter(c.navigationFilter).eq(0);if(d.length){var e=d.closest(".ui-accordion-header");e.length?b.active=e:b.active=d.closest(".ui-accordion-content").prev()}}b.active=b._findActive(b.active||c.active).addClass("ui-state-default ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top"),b.active.next().addClass("ui-accordion-content-active"),b._createIcons(),b.resize(),b.element.attr("role","tablist"),b.headers.attr("role","tab").bind("keydown.accordion",function(a){return b._keydown(a)}).next().attr("role","tabpanel"),b.headers.not(b.active||"").attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).next().hide(),b.active.length?b.active.attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}):b.headers.eq(0).attr("tabIndex",0),a.browser.safari||b.headers.find("a").attr("tabIndex",-1),c.event&&b.headers.bind(c.event.split(" ").join(".accordion ")+".accordion",function(a){b._clickHandler.call(b,a,this),a.preventDefault()})},_createIcons:function(){var b=this.options;b.icons&&(a("<span></span>").addClass("ui-icon "+b.icons.header).prependTo(this.headers),this.active.children(".ui-icon").toggleClass(b.icons.header).toggleClass(b.icons.headerSelected),this.element.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.children(".ui-icon").remove(),this.element.removeClass("ui-accordion-icons")},destroy:function(){var b=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role"),this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("tabIndex"),this.headers.find("a").removeAttr("tabIndex"),this._destroyIcons();var c=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled");return(b.autoHeight||b.fillHeight)&&c.css("height",""),a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments),b=="active"&&this.activate(c),b=="icons"&&(this._destroyIcons(),c&&this._createIcons()),b=="disabled"&&this.headers.add(this.headers.next())[c?"addClass":"removeClass"]("ui-accordion-disabled ui-state-disabled")},_keydown:function(b){if(this.options.disabled||b.altKey||b.ctrlKey)return;var c=a.ui.keyCode,d=this.headers.length,e=this.headers.index(b.target),f=!1;switch(b.keyCode){case c.RIGHT:case c.DOWN:f=this.headers[(e+1)%d];break;case c.LEFT:case c.UP:f=this.headers[(e-1+d)%d];break;case c.SPACE:case c.ENTER:this._clickHandler({target:b.target},b.target),b.preventDefault()}return f?(a(b.target).attr("tabIndex",-1),a(f).attr("tabIndex",0),f.focus(),!1):!0},resize:function(){var b=this.options,c;if(b.fillSpace){if(a.browser.msie){var d=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}c=this.element.parent().height(),a.browser.msie&&this.element.parent().css("overflow",d),this.headers.each(function(){c-=a(this).outerHeight(!0)}),this.headers.next().each(function(){a(this).height(Math.max(0,c-a(this).innerHeight()+a(this).height()))}).css("overflow","auto")}else b.autoHeight&&(c=0,this.headers.next().each(function(){c=Math.max(c,a(this).height("").height())}).height(c));return this},activate:function(a){this.options.active=a;var b=this._findActive(a)[0];return this._clickHandler({target:b},b),this},_findActive:function(b){return b?typeof b=="number"?this.headers.filter(":eq("+b+")"):this.headers.not(this.headers.not(b)):b===!1?a([]):this.headers.filter(":eq(0)")},_clickHandler:function(b,c){var d=this.options;if(d.disabled)return;if(!b.target){if(!d.collapsible)return;this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header),this.active.next().addClass("ui-accordion-content-active");var e=this.active.next(),f={options:d,newHeader:a([]),oldHeader:d.active,newContent:a([]),oldContent:e},g=this.active=a([]);this._toggle(g,e,f);return}var h=a(b.currentTarget||c),i=h[0]===this.active[0];d.active=d.collapsible&&i?!1:this.headers.index(h);if(this.running||!d.collapsible&&i)return;var j=this.active,g=h.next(),e=this.active.next(),f={options:d,newHeader:i&&d.collapsible?a([]):h,oldHeader:this.active,newContent:i&&d.collapsible?a([]):g,oldContent:e},k=this.headers.index(this.active[0])>this.headers.index(h[0]);this.active=i?a([]):h,this._toggle(g,e,f,i,k),j.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(d.icons.headerSelected).addClass(d.icons.header),i||(h.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").children(".ui-icon").removeClass(d.icons.header).addClass(d.icons.headerSelected),h.next().addClass("ui-accordion-content-active"));return},_toggle:function(b,c,d,e,f){var g=this,h=g.options;g.toShow=b,g.toHide=c,g.data=d;var i=function(){if(!g)return;return g._completed.apply(g,arguments)};g._trigger("changestart",null,g.data),g.running=c.size()===0?b.size():c.size();if(h.animated){var j={};h.collapsible&&e?j={toShow:a([]),toHide:c,complete:i,down:f,autoHeight:h.autoHeight||h.fillSpace}:j={toShow:b,toHide:c,complete:i,down:f,autoHeight:h.autoHeight||h.fillSpace},h.proxied||(h.proxied=h.animated),h.proxiedDuration||(h.proxiedDuration=h.duration),h.animated=a.isFunction(h.proxied)?h.proxied(j):h.proxied,h.duration=a.isFunction(h.proxiedDuration)?h.proxiedDuration(j):h.proxiedDuration;var k=a.ui.accordion.animations,l=h.duration,m=h.animated;m&&!k[m]&&!a.easing[m]&&(m="slide"),k[m]||(k[m]=function(a){this.slide(a,{easing:m,duration:l||700})}),k[m](j)}else h.collapsible&&e?b.toggle():(c.hide(),b.show()),i(!0);c.prev().attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).blur(),b.prev().attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}).focus()},_completed:function(a){this.running=a?0:--this.running;if(this.running)return;this.options.clearStyle&&this.toShow.add(this.toHide).css({height:"",overflow:""}),this.toHide.removeClass("ui-accordion-content-active"),this.toHide.length&&(this.toHide.parent()[0].className=this.toHide.parent()[0].className),this._trigger("change",null,this.data)}}),a.extend(a.ui.accordion,{version:"1.8.21",animations:{slide:function(b,c){b=a.extend({easing:"swing",duration:300},b,c);if(!b.toHide.size()){b.toShow.animate({height:"show",paddingTop:"show",paddingBottom:"show"},b);return}if(!b.toShow.size()){b.toHide.animate({height:"hide",paddingTop:"hide",paddingBottom:"hide"},b);return}var d=b.toShow.css("overflow"),e=0,f={},g={},h=["height","paddingTop","paddingBottom"],i,j=b.toShow;i=j[0].style.width,j.width(j.parent().width()-parseFloat(j.css("paddingLeft"))-parseFloat(j.css("paddingRight"))-(parseFloat(j.css("borderLeftWidth"))||0)-(parseFloat(j.css("borderRightWidth"))||0)),a.each(h,function(c,d){g[d]="hide";var e=(""+a.css(b.toShow[0],d)).match(/^([\d+-.]+)(.*)$/);f[d]={value:e[1],unit:e[2]||"px"}}),b.toShow.css({height:0,overflow:"hidden"}).show(),b.toHide.filter(":hidden").each(b.complete).end().filter(":visible").animate(g,{step:function(a,c){c.prop=="height"&&(e=c.end-c.start===0?0:(c.now-c.start)/(c.end-c.start)),b.toShow[0].style[c.prop]=e*f[c.prop].value+f[c.prop].unit},duration:b.duration,easing:b.easing,complete:function(){b.autoHeight||b.toShow.css("height",""),b.toShow.css({width:i,overflow:d}),b.complete()}})},bounceslide:function(a){this.slide(a,{easing:a.down?"easeOutBounce":"swing",duration:a.down?1e3:200})}}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1541 * https://github.com/jquery/jquery-ui
1542 * Includes: jquery.ui.autocomplete.js
1543 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1544 (function(a,b){var c=0;a.widget("ui.autocomplete",{options:{appendTo:"body",autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null},pending:0,_create:function(){var b=this,c=this.element[0].ownerDocument,d;this.isMultiLine=this.element.is("textarea"),this.element.addClass("ui-autocomplete-input").attr("autocomplete","off").attr({role:"textbox","aria-autocomplete":"list","aria-haspopup":"true"}).bind("keydown.autocomplete",function(c){if(b.options.disabled||b.element.propAttr("readOnly"))return;d=!1;var e=a.ui.keyCode;switch(c.keyCode){case e.PAGE_UP:b._move("previousPage",c);break;case e.PAGE_DOWN:b._move("nextPage",c);break;case e.UP:b._keyEvent("previous",c);break;case e.DOWN:b._keyEvent("next",c);break;case e.ENTER:case e.NUMPAD_ENTER:b.menu.active&&(d=!0,c.preventDefault());case e.TAB:if(!b.menu.active)return;b.menu.select(c);break;case e.ESCAPE:b.element.val(b.term),b.close(c);break;default:clearTimeout(b.searching),b.searching=setTimeout(function(){b.term!=b.element.val()&&(b.selectedItem=null,b.search(null,c))},b.options.delay)}}).bind("keypress.autocomplete",function(a){d&&(d=!1,a.preventDefault())}).bind("focus.autocomplete",function(){if(b.options.disabled)return;b.selectedItem=null,b.previous=b.element.val()}).bind("blur.autocomplete",function(a){if(b.options.disabled)return;clearTimeout(b.searching),b.closing=setTimeout(function(){b.close(a),b._change(a)},150)}),this._initSource(),this.menu=a("<ul></ul>").addClass("ui-autocomplete").appendTo(a(this.options.appendTo||"body",c)[0]).mousedown(function(c){var d=b.menu.element[0];a(c.target).closest(".ui-menu-item").length||setTimeout(function(){a(document).one("mousedown",function(c){c.target!==b.element[0]&&c.target!==d&&!a.ui.contains(d,c.target)&&b.close()})},1),setTimeout(function(){clearTimeout(b.closing)},13)}).menu({focus:function(a,c){var d=c.item.data("item.autocomplete");!1!==b._trigger("focus",a,{item:d})&&/^key/.test(a.originalEvent.type)&&b.element.val(d.value)},selected:function(a,d){var e=d.item.data("item.autocomplete"),f=b.previous;b.element[0]!==c.activeElement&&(b.element.focus(),b.previous=f,setTimeout(function(){b.previous=f,b.selectedItem=e},1)),!1!==b._trigger("select",a,{item:e})&&b.element.val(e.value),b.term=b.element.val(),b.close(a),b.selectedItem=e},blur:function(a,c){b.menu.element.is(":visible")&&b.element.val()!==b.term&&b.element.val(b.term)}}).zIndex(this.element.zIndex()+1).css({top:0,left:0}).hide().data("menu"),a.fn.bgiframe&&this.menu.element.bgiframe(),b.beforeunloadHandler=function(){b.element.removeAttr("autocomplete")},a(window).bind("beforeunload",b.beforeunloadHandler)},destroy:function(){this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete").removeAttr("role").removeAttr("aria-autocomplete").removeAttr("aria-haspopup"),this.menu.element.remove(),a(window).unbind("beforeunload",this.beforeunloadHandler),a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments),b==="source"&&this._initSource(),b==="appendTo"&&this.menu.element.appendTo(a(c||"body",this.element[0].ownerDocument)[0]),b==="disabled"&&c&&this.xhr&&this.xhr.abort()},_initSource:function(){var b=this,c,d;a.isArray(this.options.source)?(c=this.options.source,this.source=function(b,d){d(a.ui.autocomplete.filter(c,b.term))}):typeof this.options.source=="string"?(d=this.options.source,this.source=function(c,e){b.xhr&&b.xhr.abort(),b.xhr=a.ajax({url:d,data:c,dataType:"json",success:function(a,b){e(a)},error:function(){e([])}})}):this.source=this.options.source},search:function(a,b){a=a!=null?a:this.element.val(),this.term=this.element.val();if(a.length<this.options.minLength)return this.close(b);clearTimeout(this.closing);if(this._trigger("search",b)===!1)return;return this._search(a)},_search:function(a){this.pending++,this.element.addClass("ui-autocomplete-loading"),this.source({term:a},this._response())},_response:function(){var a=this,b=++c;return function(d){b===c&&a.__response(d),a.pending--,a.pending||a.element.removeClass("ui-autocomplete-loading")}},__response:function(a){!this.options.disabled&&a&&a.length?(a=this._normalize(a),this._suggest(a),this._trigger("open")):this.close()},close:function(a){clearTimeout(this.closing),this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.deactivate(),this._trigger("close",a))},_change:function(a){this.previous!==this.element.val()&&this._trigger("change",a,{item:this.selectedItem})},_normalize:function(b){return b.length&&b[0].label&&b[0].value?b:a.map(b,function(b){return typeof b=="string"?{label:b,value:b}:a.extend({label:b.label||b.value,value:b.value||b.label},b)})},_suggest:function(b){var c=this.menu.element.empty().zIndex(this.element.zIndex()+1);this._renderMenu(c,b),this.menu.deactivate(),this.menu.refresh(),c.show(),this._resizeMenu(),c.position(a.extend({of:this.element},this.options.position)),this.options.autoFocus&&this.menu.next(new a.Event("mouseover"))},_resizeMenu:function(){var a=this.menu.element;a.outerWidth(Math.max(a.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(b,c){var d=this;a.each(c,function(a,c){d._renderItem(b,c)})},_renderItem:function(b,c){return a("<li></li>").data("item.autocomplete",c).append(a("<a></a>").text(c.label)).appendTo(b)},_move:function(a,b){if(!this.menu.element.is(":visible")){this.search(null,b);return}if(this.menu.first()&&/^previous/.test(a)||this.menu.last()&&/^next/.test(a)){this.element.val(this.term),this.menu.deactivate();return}this.menu[a](b)},widget:function(){return this.menu.element},_keyEvent:function(a,b){if(!this.isMultiLine||this.menu.element.is(":visible"))this._move(a,b),b.preventDefault()}}),a.extend(a.ui.autocomplete,{escapeRegex:function(a){return a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},filter:function(b,c){var d=new RegExp(a.ui.autocomplete.escapeRegex(c),"i");return a.grep(b,function(a){return d.test(a.label||a.value||a)})}})})(jQuery),function(a){a.widget("ui.menu",{_create:function(){var b=this;this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr({role:"listbox","aria-activedescendant":"ui-active-menuitem"}).click(function(c){if(!a(c.target).closest(".ui-menu-item a").length)return;c.preventDefault(),b.select(c)}),this.refresh()},refresh:function(){var b=this,c=this.element.children("li:not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","menuitem");c.children("a").addClass("ui-corner-all").attr("tabindex",-1).mouseenter(function(c){b.activate(c,a(this).parent())}).mouseleave(function(){b.deactivate()})},activate:function(a,b){this.deactivate();if(this.hasScroll()){var c=b.offset().top-this.element.offset().top,d=this.element.scrollTop(),e=this.element.height();c<0?this.element.scrollTop(d+c):c>=e&&this.element.scrollTop(d+c-e+b.height())}this.active=b.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-menuitem").end(),this._trigger("focus",a,{item:b})},deactivate:function(){if(!this.active)return;this.active.children("a").removeClass("ui-state-hover").removeAttr("id"),this._trigger("blur"),this.active=null},next:function(a){this.move("next",".ui-menu-item:first",a)},previous:function(a){this.move("prev",".ui-menu-item:last",a)},first:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},last:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},move:function(a,b,c){if(!this.active){this.activate(c,this.element.children(b));return}var d=this.active[a+"All"](".ui-menu-item").eq(0);d.length?this.activate(c,d):this.activate(c,this.element.children(b))},nextPage:function(b){if(this.hasScroll()){if(!this.active||this.last()){this.activate(b,this.element.children(".ui-menu-item:first"));return}var c=this.active.offset().top,d=this.element.height(),e=this.element.children(".ui-menu-item").filter(function(){var b=a(this).offset().top-c-d+a(this).height();return b<10&&b>-10});e.length||(e=this.element.children(".ui-menu-item:last")),this.activate(b,e)}else this.activate(b,this.element.children(".ui-menu-item").filter(!this.active||this.last()?":first":":last"))},previousPage:function(b){if(this.hasScroll()){if(!this.active||this.first()){this.activate(b,this.element.children(".ui-menu-item:last"));return}var c=this.active.offset().top,d=this.element.height(),e=this.element.children(".ui-menu-item").filter(function(){var b=a(this).offset().top-c+d-a(this).height();return b<10&&b>-10});e.length||(e=this.element.children(".ui-menu-item:first")),this.activate(b,e)}else this.activate(b,this.element.children(".ui-menu-item").filter(!this.active||this.first()?":last":":first"))},hasScroll:function(){return this.element.height()<this.element[a.fn.prop?"prop":"attr"]("scrollHeight")},select:function(a){this._trigger("selected",a,{item:this.active})}})}(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1545 * https://github.com/jquery/jquery-ui
1546 * Includes: jquery.ui.button.js
1547 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1548 (function(a,b){var c,d,e,f,g="ui-button ui-widget ui-state-default ui-corner-all",h="ui-state-hover ui-state-active ",i="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",j=function(){var b=a(this).find(":ui-button");setTimeout(function(){b.button("refresh")},1)},k=function(b){var c=b.name,d=b.form,e=a([]);return c&&(d?e=a(d).find("[name='"+c+"']"):e=a("[name='"+c+"']",b.ownerDocument).filter(function(){return!this.form})),e};a.widget("ui.button",{options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset.button").bind("reset.button",j),typeof this.options.disabled!="boolean"?this.options.disabled=!!this.element.propAttr("disabled"):this.element.propAttr("disabled",this.options.disabled),this._determineButtonType(),this.hasTitle=!!this.buttonElement.attr("title");var b=this,h=this.options,i=this.type==="checkbox"||this.type==="radio",l="ui-state-hover"+(i?"":" ui-state-active"),m="ui-state-focus";h.label===null&&(h.label=this.buttonElement.html()),this.buttonElement.addClass(g).attr("role","button").bind("mouseenter.button",function(){if(h.disabled)return;a(this).addClass("ui-state-hover"),this===c&&a(this).addClass("ui-state-active")}).bind("mouseleave.button",function(){if(h.disabled)return;a(this).removeClass(l)}).bind("click.button",function(a){h.disabled&&(a.preventDefault(),a.stopImmediatePropagation())}),this.element.bind("focus.button",function(){b.buttonElement.addClass(m)}).bind("blur.button",function(){b.buttonElement.removeClass(m)}),i&&(this.element.bind("change.button",function(){if(f)return;b.refresh()}),this.buttonElement.bind("mousedown.button",function(a){if(h.disabled)return;f=!1,d=a.pageX,e=a.pageY}).bind("mouseup.button",function(a){if(h.disabled)return;if(d!==a.pageX||e!==a.pageY)f=!0})),this.type==="checkbox"?this.buttonElement.bind("click.button",function(){if(h.disabled||f)return!1;a(this).toggleClass("ui-state-active"),b.buttonElement.attr("aria-pressed",b.element[0].checked)}):this.type==="radio"?this.buttonElement.bind("click.button",function(){if(h.disabled||f)return!1;a(this).addClass("ui-state-active"),b.buttonElement.attr("aria-pressed","true");var c=b.element[0];k(c).not(c).map(function(){return a(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown.button",function(){if(h.disabled)return!1;a(this).addClass("ui-state-active"),c=this,a(document).one("mouseup",function(){c=null})}).bind("mouseup.button",function(){if(h.disabled)return!1;a(this).removeClass("ui-state-active")}).bind("keydown.button",function(b){if(h.disabled)return!1;(b.keyCode==a.ui.keyCode.SPACE||b.keyCode==a.ui.keyCode.ENTER)&&a(this).addClass("ui-state-active")}).bind("keyup.button",function(){a(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(b){b.keyCode===a.ui.keyCode.SPACE&&a(this).click()})),this._setOption("disabled",h.disabled),this._resetButton()},_determineButtonType:function(){this.element.is(":checkbox")?this.type="checkbox":this.element.is(":radio")?this.type="radio":this.element.is("input")?this.type="input":this.type="button";if(this.type==="checkbox"||this.type==="radio"){var a=this.element.parents().filter(":last"),b="label[for='"+this.element.attr("id")+"']";this.buttonElement=a.find(b),this.buttonElement.length||(a=a.length?a.siblings():this.element.siblings(),this.buttonElement=a.filter(b),this.buttonElement.length||(this.buttonElement=a.find(b))),this.element.addClass("ui-helper-hidden-accessible");var c=this.element.is(":checked");c&&this.buttonElement.addClass("ui-state-active"),this.buttonElement.attr("aria-pressed",c)}else this.buttonElement=this.element},widget:function(){return this.buttonElement},destroy:function(){this.element.removeClass("ui-helper-hidden-accessible"),this.buttonElement.removeClass(g+" "+h+" "+i).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html()),this.hasTitle||this.buttonElement.removeAttr("title"),a.Widget.prototype.destroy.call(this)},_setOption:function(b,c){a.Widget.prototype._setOption.apply(this,arguments);if(b==="disabled"){c?this.element.propAttr("disabled",!0):this.element.propAttr("disabled",!1);return}this._resetButton()},refresh:function(){var b=this.element.is(":disabled");b!==this.options.disabled&&this._setOption("disabled",b),this.type==="radio"?k(this.element[0]).each(function(){a(this).is(":checked")?a(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true"):a(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):this.type==="checkbox"&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if(this.type==="input"){this.options.label&&this.element.val(this.options.label);return}var b=this.buttonElement.removeClass(i),c=a("<span></span>",this.element[0].ownerDocument).addClass("ui-button-text").html(this.options.label).appendTo(b.empty()).text(),d=this.options.icons,e=d.primary&&d.secondary,f=[];d.primary||d.secondary?(this.options.text&&f.push("ui-button-text-icon"+(e?"s":d.primary?"-primary":"-secondary")),d.primary&&b.prepend("<span class='ui-button-icon-primary ui-icon "+d.primary+"'></span>"),d.secondary&&b.append("<span class='ui-button-icon-secondary ui-icon "+d.secondary+"'></span>"),this.options.text||(f.push(e?"ui-button-icons-only":"ui-button-icon-only"),this.hasTitle||b.attr("title",c))):f.push("ui-button-text-only"),b.addClass(f.join(" "))}}),a.widget("ui.buttonset",{options:{items:":button, :submit, :reset, :checkbox, :radio, a, :data(button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(b,c){b==="disabled"&&this.buttons.button("option",b,c),a.Widget.prototype._setOption.apply(this,arguments)},refresh:function(){var b=this.element.css("direction")==="rtl";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(b?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(b?"ui-corner-left":"ui-corner-right").end().end()},destroy:function(){this.element.removeClass("ui-buttonset"),this.buttons.map(function(){return a(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy"),a.Widget.prototype.destroy.call(this)}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1549 * https://github.com/jquery/jquery-ui
1550 * Includes: jquery.ui.dialog.js
1551 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1552 (function(a,b){var c="ui-dialog ui-widget ui-widget-content ui-corner-all ",d={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},e={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},f=a.attrFn||{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0,click:!0};a.widget("ui.dialog",{options:{autoOpen:!0,buttons:{},closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:!1,maxWidth:!1,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",collision:"fit",using:function(b){var c=a(this).css(b).offset().top;c<0&&a(this).css("top",b.top-c)}},resizable:!0,show:null,stack:!0,title:"",width:300,zIndex:1e3},_create:function(){this.originalTitle=this.element.attr("title"),typeof this.originalTitle!="string"&&(this.originalTitle=""),this.options.title=this.options.title||this.originalTitle;var b=this,d=b.options,e=d.title||" ",f=a.ui.dialog.getTitleId(b.element),g=(b.uiDialog=a("<div></div>")).appendTo(document.body).hide().addClass(c+d.dialogClass).css({zIndex:d.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(c){d.closeOnEscape&&!c.isDefaultPrevented()&&c.keyCode&&c.keyCode===a.ui.keyCode.ESCAPE&&(b.close(c),c.preventDefault())}).attr({role:"dialog","aria-labelledby":f}).mousedown(function(a){b.moveToTop(!1,a)}),h=b.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(g),i=(b.uiDialogTitlebar=a("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(g),j=a('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){j.addClass("ui-state-hover")},function(){j.removeClass("ui-state-hover")}).focus(function(){j.addClass("ui-state-focus")}).blur(function(){j.removeClass("ui-state-focus")}).click(function(a){return b.close(a),!1}).appendTo(i),k=(b.uiDialogTitlebarCloseText=a("<span></span>")).addClass("ui-icon ui-icon-closethick").text(d.closeText).appendTo(j),l=a("<span></span>").addClass("ui-dialog-title").attr("id",f).html(e).prependTo(i);a.isFunction(d.beforeclose)&&!a.isFunction(d.beforeClose)&&(d.beforeClose=d.beforeclose),i.find("*").add(i).disableSelection(),d.draggable&&a.fn.draggable&&b._makeDraggable(),d.resizable&&a.fn.resizable&&b._makeResizable(),b._createButtons(d.buttons),b._isOpen=!1,a.fn.bgiframe&&g.bgiframe()},_init:function(){this.options.autoOpen&&this.open()},destroy:function(){var a=this;return a.overlay&&a.overlay.destroy(),a.uiDialog.hide(),a.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body"),a.uiDialog.remove(),a.originalTitle&&a.element.attr("title",a.originalTitle),a},widget:function(){return this.uiDialog},close:function(b){var c=this,d,e;if(!1===c._trigger("beforeClose",b))return;return c.overlay&&c.overlay.destroy(),c.uiDialog.unbind("keypress.ui-dialog"),c._isOpen=!1,c.options.hide?c.uiDialog.hide(c.options.hide,function(){c._trigger("close",b)}):(c.uiDialog.hide(),c._trigger("close",b)),a.ui.dialog.overlay.resize(),c.options.modal&&(d=0,a(".ui-dialog").each(function(){this!==c.uiDialog[0]&&(e=a(this).css("z-index"),isNaN(e)||(d=Math.max(d,e)))}),a.ui.dialog.maxZ=d),c},isOpen:function(){return this._isOpen},moveToTop:function(b,c){var d=this,e=d.options,f;return e.modal&&!b||!e.stack&&!e.modal?d._trigger("focus",c):(e.zIndex>a.ui.dialog.maxZ&&(a.ui.dialog.maxZ=e.zIndex),d.overlay&&(a.ui.dialog.maxZ+=1,d.overlay.$el.css("z-index",a.ui.dialog.overlay.maxZ=a.ui.dialog.maxZ)),f={scrollTop:d.element.scrollTop(),scrollLeft:d.element.scrollLeft()},a.ui.dialog.maxZ+=1,d.uiDialog.css("z-index",a.ui.dialog.maxZ),d.element.attr(f),d._trigger("focus",c),d)},open:function(){if(this._isOpen)return;var b=this,c=b.options,d=b.uiDialog;return b.overlay=c.modal?new a.ui.dialog.overlay(b):null,b._size(),b._position(c.position),d.show(c.show),b.moveToTop(!0),c.modal&&d.bind("keydown.ui-dialog",function(b){if(b.keyCode!==a.ui.keyCode.TAB)return;var c=a(":tabbable",this),d=c.filter(":first"),e=c.filter(":last");if(b.target===e[0]&&!b.shiftKey)return d.focus(1),!1;if(b.target===d[0]&&b.shiftKey)return e.focus(1),!1}),a(b.element.find(":tabbable").get().concat(d.find(".ui-dialog-buttonpane :tabbable").get().concat(d.get()))).eq(0).focus(),b._isOpen=!0,b._trigger("open"),b},_createButtons:function(b){var c=this,d=!1,e=a("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),g=a("<div></div>").addClass("ui-dialog-buttonset").appendTo(e);c.uiDialog.find(".ui-dialog-buttonpane").remove(),typeof b=="object"&&b!==null&&a.each(b,function(){return!(d=!0)}),d&&(a.each(b,function(b,d){d=a.isFunction(d)?{click:d,text:b}:d;var e=a('<button type="button"></button>').click(function(){d.click.apply(c.element[0],arguments)}).appendTo(g);a.each(d,function(a,b){if(a==="click")return;a in f?e[a](b):e.attr(a,b)}),a.fn.button&&e.button()}),e.appendTo(c.uiDialog))},_makeDraggable:function(){function f(a){return{position:a.position,offset:a.offset}}var b=this,c=b.options,d=a(document),e;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(d,g){e=c.height==="auto"?"auto":a(this).height(),a(this).height(a(this).height()).addClass("ui-dialog-dragging"),b._trigger("dragStart",d,f(g))},drag:function(a,c){b._trigger("drag",a,f(c))},stop:function(g,h){c.position=[h.position.left-d.scrollLeft(),h.position.top-d.scrollTop()],a(this).removeClass("ui-dialog-dragging").height(e),b._trigger("dragStop",g,f(h)),a.ui.dialog.overlay.resize()}})},_makeResizable:function(c){function h(a){return{originalPosition:a.originalPosition,originalSize:a.originalSize,position:a.position,size:a.size}}c=c===b?this.options.resizable:c;var d=this,e=d.options,f=d.uiDialog.css("position"),g=typeof c=="string"?c:"n,e,s,w,se,sw,ne,nw";d.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:d.element,maxWidth:e.maxWidth,maxHeight:e.maxHeight,minWidth:e.minWidth,minHeight:d._minHeight(),handles:g,start:function(b,c){a(this).addClass("ui-dialog-resizing"),d._trigger("resizeStart",b,h(c))},resize:function(a,b){d._trigger("resize",a,h(b))},stop:function(b,c){a(this).removeClass("ui-dialog-resizing"),e.height=a(this).height(),e.width=a(this).width(),d._trigger("resizeStop",b,h(c)),a.ui.dialog.overlay.resize()}}).css("position",f).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(b){var c=[],d=[0,0],e;if(b){if(typeof b=="string"||typeof b=="object"&&"0"in b)c=b.split?b.split(" "):[b[0],b[1]],c.length===1&&(c[1]=c[0]),a.each(["left","top"],function(a,b){+c[a]===c[a]&&(d[a]=c[a],c[a]=b)}),b={my:c.join(" "),at:c.join(" "),offset:d.join(" ")};b=a.extend({},a.ui.dialog.prototype.options.position,b)}else b=a.ui.dialog.prototype.options.position;e=this.uiDialog.is(":visible"),e||this.uiDialog.show(),this.uiDialog.css({top:0,left:0}).position(a.extend({of:window},b)),e||this.uiDialog.hide()},_setOptions:function(b){var c=this,f={},g=!1;a.each(b,function(a,b){c._setOption(a,b),a in d&&(g=!0),a in e&&(f[a]=b)}),g&&this._size(),this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option",f)},_setOption:function(b,d){var e=this,f=e.uiDialog;switch(b){case"beforeclose":b="beforeClose";break;case"buttons":e._createButtons(d);break;case"closeText":e.uiDialogTitlebarCloseText.text(""+d);break;case"dialogClass":f.removeClass(e.options.dialogClass).addClass(c+d);break;case"disabled":d?f.addClass("ui-dialog-disabled"):f.removeClass("ui-dialog-disabled");break;case"draggable":var g=f.is(":data(draggable)");g&&!d&&f.draggable("destroy"),!g&&d&&e._makeDraggable();break;case"position":e._position(d);break;case"resizable":var h=f.is(":data(resizable)");h&&!d&&f.resizable("destroy"),h&&typeof d=="string"&&f.resizable("option","handles",d),!h&&d!==!1&&e._makeResizable(d);break;case"title":a(".ui-dialog-title",e.uiDialogTitlebar).html(""+(d||" "))}a.Widget.prototype._setOption.apply(e,arguments)},_size:function(){var b=this.options,c,d,e=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0}),b.minWidth>b.width&&(b.width=b.minWidth),c=this.uiDialog.css({height:"auto",width:b.width}).height(),d=Math.max(0,b.minHeight-c);if(b.height==="auto")if(a.support.minHeight)this.element.css({minHeight:d,height:"auto"});else{this.uiDialog.show();var f=this.element.css("height","auto").height();e||this.uiDialog.hide(),this.element.height(Math.max(f,d))}else this.element.height(Math.max(b.height-c,0));this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())}}),a.extend(a.ui.dialog,{version:"1.8.21",uuid:0,maxZ:0,getTitleId:function(a){var b=a.attr("id");return b||(this.uuid+=1,b=this.uuid),"ui-dialog-title-"+b},overlay:function(b){this.$el=a.ui.dialog.overlay.create(b)}}),a.extend(a.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:a.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "),create:function(b){this.instances.length===0&&(setTimeout(function(){a.ui.dialog.overlay.instances.length&&a(document).bind(a.ui.dialog.overlay.events,function(b){if(a(b.target).zIndex()<a.ui.dialog.overlay.maxZ)return!1})},1),a(document).bind("keydown.dialog-overlay",function(c){b.options.closeOnEscape&&!c.isDefaultPrevented()&&c.keyCode&&c.keyCode===a.ui.keyCode.ESCAPE&&(b.close(c),c.preventDefault())}),a(window).bind("resize.dialog-overlay",a.ui.dialog.overlay.resize));var c=(this.oldInstances.pop()||a("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});return a.fn.bgiframe&&c.bgiframe(),this.instances.push(c),c},destroy:function(b){var c=a.inArray(b,this.instances);c!=-1&&this.oldInstances.push(this.instances.splice(c,1)[0]),this.instances.length===0&&a([document,window]).unbind(".dialog-overlay"),b.remove();var d=0;a.each(this.instances,function(){d=Math.max(d,this.css("z-index"))}),this.maxZ=d},height:function(){var b,c;return a.browser.msie&&a.browser.version<7?(b=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),c=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight),b<c?a(window).height()+"px":b+"px"):a(document).height()+"px"},width:function(){var b,c;return a.browser.msie?(b=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth),c=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth),b<c?a(window).width()+"px":b+"px"):a(document).width()+"px"},resize:function(){var b=a([]);a.each(a.ui.dialog.overlay.instances,function(){b=b.add(this)}),b.css({width:0,height:0}).css({width:a.ui.dialog.overlay.width(),height:a.ui.dialog.overlay.height()})}}),a.extend(a.ui.dialog.overlay.prototype,{destroy:function(){a.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1553 * https://github.com/jquery/jquery-ui
1554 * Includes: jquery.ui.slider.js
1555 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1556 (function(a,b){var c=5;a.widget("ui.slider",a.ui.mouse,{widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null},_create:function(){var b=this,d=this.options,e=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),f="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",g=d.values&&d.values.length||1,h=[];this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"+(d.disabled?" ui-slider-disabled ui-disabled":"")),this.range=a([]),d.range&&(d.range===!0&&(d.values||(d.values=[this._valueMin(),this._valueMin()]),d.values.length&&d.values.length!==2&&(d.values=[d.values[0],d.values[0]])),this.range=a("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(d.range==="min"||d.range==="max"?" ui-slider-range-"+d.range:"")));for(var i=e.length;i<g;i+=1)h.push(f);this.handles=e.add(a(h.join("")).appendTo(b.element)),this.handle=this.handles.eq(0),this.handles.add(this.range).filter("a").click(function(a){a.preventDefault()}).hover(function(){d.disabled||a(this).addClass("ui-state-hover")},function(){a(this).removeClass("ui-state-hover")}).focus(function(){d.disabled?a(this).blur():(a(".ui-slider .ui-state-focus").removeClass("ui-state-focus"),a(this).addClass("ui-state-focus"))}).blur(function(){a(this).removeClass("ui-state-focus")}),this.handles.each(function(b){a(this).data("index.ui-slider-handle",b)}),this.handles.keydown(function(d){var e=a(this).data("index.ui-slider-handle"),f,g,h,i;if(b.options.disabled)return;switch(d.keyCode){case a.ui.keyCode.HOME:case a.ui.keyCode.END:case a.ui.keyCode.PAGE_UP:case a.ui.keyCode.PAGE_DOWN:case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:d.preventDefault();if(!b._keySliding){b._keySliding=!0,a(this).addClass("ui-state-active"),f=b._start(d,e);if(f===!1)return}}i=b.options.step,b.options.values&&b.options.values.length?g=h=b.values(e):g=h=b.value();switch(d.keyCode){case a.ui.keyCode.HOME:h=b._valueMin();break;case a.ui.keyCode.END:h=b._valueMax();break;case a.ui.keyCode.PAGE_UP:h=b._trimAlignValue(g+(b._valueMax()-b._valueMin())/c);break;case a.ui.keyCode.PAGE_DOWN:h=b._trimAlignValue(g-(b._valueMax()-b._valueMin())/c);break;case a.ui.keyCode.UP:case a.ui.keyCode.RIGHT:if(g===b._valueMax())return;h=b._trimAlignValue(g+i);break;case a.ui.keyCode.DOWN:case a.ui.keyCode.LEFT:if(g===b._valueMin())return;h=b._trimAlignValue(g-i)}b._slide(d,e,h)}).keyup(function(c){var d=a(this).data("index.ui-slider-handle");b._keySliding&&(b._keySliding=!1,b._stop(c,d),b._change(c,d),a(this).removeClass("ui-state-active"))}),this._refreshValue(),this._animateOff=!1},destroy:function(){return this.handles.remove(),this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider"),this._mouseDestroy(),this},_mouseCapture:function(b){var c=this.options,d,e,f,g,h,i,j,k,l;return c.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),d={x:b.pageX,y:b.pageY},e=this._normValueFromMouse(d),f=this._valueMax()-this._valueMin()+1,h=this,this.handles.each(function(b){var c=Math.abs(e-h.values(b));f>c&&(f=c,g=a(this),i=b)}),c.range===!0&&this.values(1)===c.min&&(i+=1,g=a(this.handles[i])),j=this._start(b,i),j===!1?!1:(this._mouseSliding=!0,h._handleIndex=i,g.addClass("ui-state-active").focus(),k=g.offset(),l=!a(b.target).parents().andSelf().is(".ui-slider-handle"),this._clickOffset=l?{left:0,top:0}:{left:b.pageX-k.left-g.width()/2,top:b.pageY-k.top-g.height()/2-(parseInt(g.css("borderTopWidth"),10)||0)-(parseInt(g.css("borderBottomWidth"),10)||0)+(parseInt(g.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(b,i,e),this._animateOff=!0,!0))},_mouseStart:function(a){return!0},_mouseDrag:function(a){var b={x:a.pageX,y:a.pageY},c=this._normValueFromMouse(b);return this._slide(a,this._handleIndex,c),!1},_mouseStop:function(a){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(a,this._handleIndex),this._change(a,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(a){var b,c,d,e,f;return this.orientation==="horizontal"?(b=this.elementSize.width,c=a.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(b=this.elementSize.height,c=a.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),d=c/b,d>1&&(d=1),d<0&&(d=0),this.orientation==="vertical"&&(d=1-d),e=this._valueMax()-this._valueMin(),f=this._valueMin()+d*e,this._trimAlignValue(f)},_start:function(a,b){var c={handle:this.handles[b],value:this.value()};return this.options.values&&this.options.values.length&&(c.value=this.values(b),c.values=this.values()),this._trigger("start",a,c)},_slide:function(a,b,c){var d,e,f;this.options.values&&this.options.values.length?(d=this.values(b?0:1),this.options.values.length===2&&this.options.range===!0&&(b===0&&c>d||b===1&&c<d)&&(c=d),c!==this.values(b)&&(e=this.values(),e[b]=c,f=this._trigger("slide",a,{handle:this.handles[b],value:c,values:e}),d=this.values(b?0:1),f!==!1&&this.values(b,c,!0))):c!==this.value()&&(f=this._trigger("slide",a,{handle:this.handles[b],value:c}),f!==!1&&this.value(c))},_stop:function(a,b){var c={handle:this.handles[b],value:this.value()};this.options.values&&this.options.values.length&&(c.value=this.values(b),c.values=this.values()),this._trigger("stop",a,c)},_change:function(a,b){if(!this._keySliding&&!this._mouseSliding){var c={handle:this.handles[b],value:this.value()};this.options.values&&this.options.values.length&&(c.value=this.values(b),c.values=this.values()),this._trigger("change",a,c)}},value:function(a){if(arguments.length){this.options.value=this._trimAlignValue(a),this._refreshValue(),this._change(null,0);return}return this._value()},values:function(b,c){var d,e,f;if(arguments.length>1){this.options.values[b]=this._trimAlignValue(c),this._refreshValue(),this._change(null,b);return}if(!arguments.length)return this._values();if(!a.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(b):this.value();d=this.options.values,e=arguments[0];for(f=0;f<d.length;f+=1)d[f]=this._trimAlignValue(e[f]),this._change(null,f);this._refreshValue()},_setOption:function(b,c){var d,e=0;a.isArray(this.options.values)&&(e=this.options.values.length),a.Widget.prototype._setOption.apply(this,arguments);switch(b){case"disabled":c?(this.handles.filter(".ui-state-focus").blur(),this.handles.removeClass("ui-state-hover"),this.handles.propAttr("disabled",!0),this.element.addClass("ui-disabled")):(this.handles.propAttr("disabled",!1),this.element.removeClass("ui-disabled"));break;case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":this._animateOff=!0,this._refreshValue();for(d=0;d<e;d+=1)this._change(null,d);this._animateOff=!1}},_value:function(){var a=this.options.value;return a=this._trimAlignValue(a),a},_values:function(a){var b,c,d;if(arguments.length)return b=this.options.values[a],b=this._trimAlignValue(b),b;c=this.options.values.slice();for(d=0;d<c.length;d+=1)c[d]=this._trimAlignValue(c[d]);return c},_trimAlignValue:function(a){if(a<=this._valueMin())return this._valueMin();if(a>=this._valueMax())return this._valueMax();var b=this.options.step>0?this.options.step:1,c=(a-this._valueMin())%b,d=a-c;return Math.abs(c)*2>=b&&(d+=c>0?b:-b),parseFloat(d.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var b=this.options.range,c=this.options,d=this,e=this._animateOff?!1:c.animate,f,g={},h,i,j,k;this.options.values&&this.options.values.length?this.handles.each(function(b,i){f=(d.values(b)-d._valueMin())/(d._valueMax()-d._valueMin())*100,g[d.orientation==="horizontal"?"left":"bottom"]=f+"%",a(this).stop(1,1)[e?"animate":"css"](g,c.animate),d.options.range===!0&&(d.orientation==="horizontal"?(b===0&&d.range.stop(1,1)[e?"animate":"css"]({left:f+"%"},c.animate),b===1&&d.range[e?"animate":"css"]({width:f-h+"%"},{queue:!1,duration:c.animate})):(b===0&&d.range.stop(1,1)[e?"animate":"css"]({bottom:f+"%"},c.animate),b===1&&d.range[e?"animate":"css"]({height:f-h+"%"},{queue:!1,duration:c.animate}))),h=f}):(i=this.value(),j=this._valueMin(),k=this._valueMax(),f=k!==j?(i-j)/(k-j)*100:0,g[d.orientation==="horizontal"?"left":"bottom"]=f+"%",this.handle.stop(1,1)[e?"animate":"css"](g,c.animate),b==="min"&&this.orientation==="horizontal"&&this.range.stop(1,1)[e?"animate":"css"]({width:f+"%"},c.animate),b==="max"&&this.orientation==="horizontal"&&this.range[e?"animate":"css"]({width:100-f+"%"},{queue:!1,duration:c.animate}),b==="min"&&this.orientation==="vertical"&&this.range.stop(1,1)[e?"animate":"css"]({height:f+"%"},c.animate),b==="max"&&this.orientation==="vertical"&&this.range[e?"animate":"css"]({height:100-f+"%"},{queue:!1,duration:c.animate}))}}),a.extend(a.ui.slider,{version:"1.8.21"})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1557 * https://github.com/jquery/jquery-ui
1558 * Includes: jquery.ui.tabs.js
1559 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1560 (function(a,b){function e(){return++c}function f(){return++d}var c=0,d=0;a.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:!1,cookie:null,collapsible:!1,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading…</em>",tabTemplate:"<li><a href='#{href}'><span>#{label}</span></a></li>"},_create:function(){this._tabify(!0)},_setOption:function(a,b){if(a=="selected"){if(this.options.collapsible&&b==this.options.selected)return;this.select(b)}else this.options[a]=b,this._tabify()},_tabId:function(a){return a.title&&a.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF-]/g,"")||this.options.idPrefix+e()},_sanitizeSelector:function(a){return a.replace(/:/g,"\\:")},_cookie:function(){var b=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+f());return a.cookie.apply(null,[b].concat(a.makeArray(arguments)))},_ui:function(a,b){return{tab:a,panel:b,index:this.anchors.index(a)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var b=a(this);b.html(b.data("label.tabs")).removeData("label.tabs")})},_tabify:function(c){function m(b,c){b.css("display",""),!a.support.opacity&&c.opacity&&b[0].style.removeAttribute("filter")}var d=this,e=this.options,f=/^#.+/;this.list=this.element.find("ol,ul").eq(0),this.lis=a(" > li:has(a[href])",this.list),this.anchors=this.lis.map(function(){return a("a",this)[0]}),this.panels=a([]),this.anchors.each(function(b,c){var g=a(c).attr("href"),h=g.split("#")[0],i;h&&(h===location.toString().split("#")[0]||(i=a("base")[0])&&h===i.href)&&(g=c.hash,c.href=g);if(f.test(g))d.panels=d.panels.add(d.element.find(d._sanitizeSelector(g)));else if(g&&g!=="#"){a.data(c,"href.tabs",g),a.data(c,"load.tabs",g.replace(/#.*$/,""));var j=d._tabId(c);c.href="#"+j;var k=d.element.find("#"+j);k.length||(k=a(e.panelTemplate).attr("id",j).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(d.panels[b-1]||d.list),k.data("destroy.tabs",!0)),d.panels=d.panels.add(k)}else e.disabled.push(b)}),c?(this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all"),this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"),this.lis.addClass("ui-state-default ui-corner-top"),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom"),e.selected===b?(location.hash&&this.anchors.each(function(a,b){if(b.hash==location.hash)return e.selected=a,!1}),typeof e.selected!="number"&&e.cookie&&(e.selected=parseInt(d._cookie(),10)),typeof e.selected!="number"&&this.lis.filter(".ui-tabs-selected").length&&(e.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))),e.selected=e.selected||(this.lis.length?0:-1)):e.selected===null&&(e.selected=-1),e.selected=e.selected>=0&&this.anchors[e.selected]||e.selected<0?e.selected:0,e.disabled=a.unique(e.disabled.concat(a.map(this.lis.filter(".ui-state-disabled"),function(a,b){return d.lis.index(a)}))).sort(),a.inArray(e.selected,e.disabled)!=-1&&e.disabled.splice(a.inArray(e.selected,e.disabled),1),this.panels.addClass("ui-tabs-hide"),this.lis.removeClass("ui-tabs-selected ui-state-active"),e.selected>=0&&this.anchors.length&&(d.element.find(d._sanitizeSelector(d.anchors[e.selected].hash)).removeClass("ui-tabs-hide"),this.lis.eq(e.selected).addClass("ui-tabs-selected ui-state-active"),d.element.queue("tabs",function(){d._trigger("show",null,d._ui(d.anchors[e.selected],d.element.find(d._sanitizeSelector(d.anchors[e.selected].hash))[0]))}),this.load(e.selected)),a(window).bind("unload",function(){d.lis.add(d.anchors).unbind(".tabs"),d.lis=d.anchors=d.panels=null})):e.selected=this.lis.index(this.lis.filter(".ui-tabs-selected")),this.element[e.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible"),e.cookie&&this._cookie(e.selected,e.cookie);for(var g=0,h;h=this.lis[g];g++)a(h)[a.inArray(g,e.disabled)!=-1&&!a(h).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");e.cache===!1&&this.anchors.removeData("cache.tabs"),this.lis.add(this.anchors).unbind(".tabs");if(e.event!=="mouseover"){var i=function(a,b){b.is(":not(.ui-state-disabled)")&&b.addClass("ui-state-"+a)},j=function(a,b){b.removeClass("ui-state-"+a)};this.lis.bind("mouseover.tabs",function(){i("hover",a(this))}),this.lis.bind("mouseout.tabs",function(){j("hover",a(this))}),this.anchors.bind("focus.tabs",function(){i("focus",a(this).closest("li"))}),this.anchors.bind("blur.tabs",function(){j("focus",a(this).closest("li"))})}var k,l;e.fx&&(a.isArray(e.fx)?(k=e.fx[0],l=e.fx[1]):k=l=e.fx);var n=l?function(b,c){a(b).closest("li").addClass("ui-tabs-selected ui-state-active"),c.hide().removeClass("ui-tabs-hide").animate(l,l.duration||"normal",function(){m(c,l),d._trigger("show",null,d._ui(b,c[0]))})}:function(b,c){a(b).closest("li").addClass("ui-tabs-selected ui-state-active"),c.removeClass("ui-tabs-hide"),d._trigger("show",null,d._ui(b,c[0]))},o=k?function(a,b){b.animate(k,k.duration||"normal",function(){d.lis.removeClass("ui-tabs-selected ui-state-active"),b.addClass("ui-tabs-hide"),m(b,k),d.element.dequeue("tabs")})}:function(a,b,c){d.lis.removeClass("ui-tabs-selected ui-state-active"),b.addClass("ui-tabs-hide"),d.element.dequeue("tabs")};this.anchors.bind(e.event+".tabs",function(){var b=this,c=a(b).closest("li"),f=d.panels.filter(":not(.ui-tabs-hide)"),g=d.element.find(d._sanitizeSelector(b.hash));if(c.hasClass("ui-tabs-selected")&&!e.collapsible||c.hasClass("ui-state-disabled")||c.hasClass("ui-state-processing")||d.panels.filter(":animated").length||d._trigger("select",null,d._ui(this,g[0]))===!1)return this.blur(),!1;e.selected=d.anchors.index(this),d.abort();if(e.collapsible){if(c.hasClass("ui-tabs-selected"))return e.selected=-1,e.cookie&&d._cookie(e.selected,e.cookie),d.element.queue("tabs",function(){o(b,f)}).dequeue("tabs"),this.blur(),!1;if(!f.length)return e.cookie&&d._cookie(e.selected,e.cookie),d.element.queue("tabs",function(){n(b,g)}),d.load(d.anchors.index(this)),this.blur(),!1}e.cookie&&d._cookie(e.selected,e.cookie);if(g.length)f.length&&d.element.queue("tabs",function(){o(b,f)}),d.element.queue("tabs",function(){n(b,g)}),d.load(d.anchors.index(this));else throw"jQuery UI Tabs: Mismatching fragment identifier.";a.browser.msie&&this.blur()}),this.anchors.bind("click.tabs",function(){return!1})},_getIndex:function(a){return typeof a=="string"&&(a=this.anchors.index(this.anchors.filter("[href$='"+a+"']"))),a},destroy:function(){var b=this.options;return this.abort(),this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs"),this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all"),this.anchors.each(function(){var b=a.data(this,"href.tabs");b&&(this.href=b);var c=a(this).unbind(".tabs");a.each(["href","load","cache"],function(a,b){c.removeData(b+".tabs")})}),this.lis.unbind(".tabs").add(this.panels).each(function(){a.data(this,"destroy.tabs")?a(this).remove():a(this).removeClass(["ui-state-default","ui-corner-top","ui-tabs-selected","ui-state-active","ui-state-hover","ui-state-focus","ui-state-disabled","ui-tabs-panel","ui-widget-content","ui-corner-bottom","ui-tabs-hide"].join(" "))}),b.cookie&&this._cookie(null,b.cookie),this},add:function(c,d,e){e===b&&(e=this.anchors.length);var f=this,g=this.options,h=a(g.tabTemplate.replace(/#\{href\}/g,c).replace(/#\{label\}/g,d)),i=c.indexOf("#")?this._tabId(a("a",h)[0]):c.replace("#","");h.addClass("ui-state-default ui-corner-top").data("destroy.tabs",!0);var j=f.element.find("#"+i);return j.length||(j=a(g.panelTemplate).attr("id",i).data("destroy.tabs",!0)),j.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide"),e>=this.lis.length?(h.appendTo(this.list),j.appendTo(this.list[0].parentNode)):(h.insertBefore(this.lis[e]),j.insertBefore(this.panels[e])),g.disabled=a.map(g.disabled,function(a,b){return a>=e?++a:a}),this._tabify(),this.anchors.length==1&&(g.selected=0,h.addClass("ui-tabs-selected ui-state-active"),j.removeClass("ui-tabs-hide"),this.element.queue("tabs",function(){f._trigger("show",null,f._ui(f.anchors[0],f.panels[0]))}),this.load(0)),this._trigger("add",null,this._ui(this.anchors[e],this.panels[e])),this},remove:function(b){b=this._getIndex(b);var c=this.options,d=this.lis.eq(b).remove(),e=this.panels.eq(b).remove();return d.hasClass("ui-tabs-selected")&&this.anchors.length>1&&this.select(b+(b+1<this.anchors.length?1:-1)),c.disabled=a.map(a.grep(c.disabled,function(a,c){return a!=b}),function(a,c){return a>=b?--a:a}),this._tabify(),this._trigger("remove",null,this._ui(d.find("a")[0],e[0])),this},enable:function(b){b=this._getIndex(b);var c=this.options;if(a.inArray(b,c.disabled)==-1)return;return this.lis.eq(b).removeClass("ui-state-disabled"),c.disabled=a.grep(c.disabled,function(a,c){return a!=b}),this._trigger("enable",null,this._ui(this.anchors[b],this.panels[b])),this},disable:function(a){a=this._getIndex(a);var b=this,c=this.options;return a!=c.selected&&(this.lis.eq(a).addClass("ui-state-disabled"),c.disabled.push(a),c.disabled.sort(),this._trigger("disable",null,this._ui(this.anchors[a],this.panels[a]))),this},select:function(a){a=this._getIndex(a);if(a==-1)if(this.options.collapsible&&this.options.selected!=-1)a=this.options.selected;else return this;return this.anchors.eq(a).trigger(this.options.event+".tabs"),this},load:function(b){b=this._getIndex(b);var c=this,d=this.options,e=this.anchors.eq(b)[0],f=a.data(e,"load.tabs");this.abort();if(!f||this.element.queue("tabs").length!==0&&a.data(e,"cache.tabs")){this.element.dequeue("tabs");return}this.lis.eq(b).addClass("ui-state-processing");if(d.spinner){var g=a("span",e);g.data("label.tabs",g.html()).html(d.spinner)}return this.xhr=a.ajax(a.extend({},d.ajaxOptions,{url:f,success:function(f,g){c.element.find(c._sanitizeSelector(e.hash)).html(f),c._cleanup(),d.cache&&a.data(e,"cache.tabs",!0),c._trigger("load",null,c._ui(c.anchors[b],c.panels[b]));try{d.ajaxOptions.success(f,g)}catch(h){}},error:function(a,f,g){c._cleanup(),c._trigger("load",null,c._ui(c.anchors[b],c.panels[b]));try{d.ajaxOptions.error(a,f,b,e)}catch(g){}}})),c.element.dequeue("tabs"),this},abort:function(){return this.element.queue([]),this.panels.stop(!1,!0),this.element.queue("tabs",this.element.queue("tabs").splice(-2,2)),this.xhr&&(this.xhr.abort(),delete this.xhr),this._cleanup(),this},url:function(a,b){return this.anchors.eq(a).removeData("cache.tabs").data("load.tabs",b),this},length:function(){return this.anchors.length}}),a.extend(a.ui.tabs,{version:"1.8.21"}),a.extend(a.ui.tabs.prototype,{rotation:null,rotate:function(a,b){var c=this,d=this.options,e=c._rotate||(c._rotate=function(b){clearTimeout(c.rotation),c.rotation=setTimeout(function(){var a=d.selected;c.select(++a<c.anchors.length?a:0)},a),b&&b.stopPropagation()}),f=c._unrotate||(c._unrotate=b?function(a){e()}:function(a){a.clientX&&c.rotate(null)});return a?(this.element.bind("tabsshow",e),this.anchors.bind(d.event+".tabs",f),e()):(clearTimeout(c.rotation),this.element.unbind("tabsshow",e),this.anchors.unbind(d.event+".tabs",f),delete this._rotate,delete this._unrotate),this}})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1561 * https://github.com/jquery/jquery-ui
1562 * Includes: jquery.ui.datepicker.js
1563 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1564 (function($,undefined){function Datepicker(){this.debug=!1,this._curInst=null,this._keyEvent=!1,this._disabledInputs=[],this._datepickerShowing=!1,this._inDialog=!1,this._mainDivId="ui-datepicker-div",this._inlineClass="ui-datepicker-inline",this._appendClass="ui-datepicker-append",this._triggerClass="ui-datepicker-trigger",this._dialogClass="ui-datepicker-dialog",this._disableClass="ui-datepicker-disabled",this._unselectableClass="ui-datepicker-unselectable",this._currentClass="ui-datepicker-current-day",this._dayOverClass="ui-datepicker-days-cell-over",this.regional=[],this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1},$.extend(this._defaults,this.regional[""]),this.dpDiv=bindHover($('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}function bindHover(a){var b="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return a.bind("mouseout",function(a){var c=$(a.target).closest(b);if(!c.length)return;c.removeClass("ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover")}).bind("mouseover",function(c){var d=$(c.target).closest(b);if($.datepicker._isDisabledDatepicker(instActive.inline?a.parent()[0]:instActive.input[0])||!d.length)return;d.parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),d.addClass("ui-state-hover"),d.hasClass("ui-datepicker-prev")&&d.addClass("ui-datepicker-prev-hover"),d.hasClass("ui-datepicker-next")&&d.addClass("ui-datepicker-next-hover")})}function extendRemove(a,b){$.extend(a,b);for(var c in b)if(b[c]==null||b[c]==undefined)a[c]=b[c];return a}function isArray(a){return a&&($.browser.safari&&typeof a=="object"&&a.length||a.constructor&&a.constructor.toString().match(/\Array\(\)/))}$.extend($.ui,{datepicker:{version:"1.8.21"}});var PROP_NAME="datepicker",dpuuid=(new Date).getTime(),instActive;$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function(){this.debug&&console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(a){return extendRemove(this._defaults,a||{}),this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase(),inline=nodeName=="div"||nodeName=="span";target.id||(this.uuid+=1,target.id="dp"+this.uuid);var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{}),nodeName=="input"?this._connectDatepicker(target,inst):inline&&this._inlineDatepicker(target,inst)},_newInst:function(a,b){var c=a[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1");return{id:c,input:a,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:b,dpDiv:b?bindHover($('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')):this.dpDiv}},_connectDatepicker:function(a,b){var c=$(a);b.append=$([]),b.trigger=$([]);if(c.hasClass(this.markerClassName))return;this._attachments(c,b),c.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(a,c,d){b.settings[c]=d}).bind("getData.datepicker",function(a,c){return this._get(b,c)}),this._autoSize(b),$.data(a,PROP_NAME,b),b.settings.disabled&&this._disableDatepicker(a)},_attachments:function(a,b){var c=this._get(b,"appendText"),d=this._get(b,"isRTL");b.append&&b.append.remove(),c&&(b.append=$('<span class="'+this._appendClass+'">'+c+"</span>"),a[d?"before":"after"](b.append)),a.unbind("focus",this._showDatepicker),b.trigger&&b.trigger.remove();var e=this._get(b,"showOn");(e=="focus"||e=="both")&&a.focus(this._showDatepicker);if(e=="button"||e=="both"){var f=this._get(b,"buttonText"),g=this._get(b,"buttonImage");b.trigger=$(this._get(b,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:g,alt:f,title:f}):$('<button type="button"></button>').addClass(this._triggerClass).html(g==""?f:$("<img/>").attr({src:g,alt:f,title:f}))),a[d?"before":"after"](b.trigger),b.trigger.click(function(){return $.datepicker._datepickerShowing&&$.datepicker._lastInput==a[0]?$.datepicker._hideDatepicker():$.datepicker._datepickerShowing&&$.datepicker._lastInput!=a[0]?($.datepicker._hideDatepicker(),$.datepicker._showDatepicker(a[0])):$.datepicker._showDatepicker(a[0]),!1})}},_autoSize:function(a){if(this._get(a,"autoSize")&&!a.inline){var b=new Date(2009,11,20),c=this._get(a,"dateFormat");if(c.match(/[DM]/)){var d=function(a){var b=0,c=0;for(var d=0;d<a.length;d++)a[d].length>b&&(b=a[d].length,c=d);return c};b.setMonth(d(this._get(a,c.match(/MM/)?"monthNames":"monthNamesShort"))),b.setDate(d(this._get(a,c.match(/DD/)?"dayNames":"dayNamesShort"))+20-b.getDay())}a.input.attr("size",this._formatDate(a,b).length)}},_inlineDatepicker:function(a,b){var c=$(a);if(c.hasClass(this.markerClassName))return;c.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker",function(a,c,d){b.settings[c]=d}).bind("getData.datepicker",function(a,c){return this._get(b,c)}),$.data(a,PROP_NAME,b),this._setDate(b,this._getDefaultDate(b),!0),this._updateDatepicker(b),this._updateAlternate(b),b.settings.disabled&&this._disableDatepicker(a),b.dpDiv.css("display","block")},_dialogDatepicker:function(a,b,c,d,e){var f=this._dialogInst;if(!f){this.uuid+=1;var g="dp"+this.uuid;this._dialogInput=$('<input type="text" id="'+g+'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>'),this._dialogInput.keydown(this._doKeyDown),$("body").append(this._dialogInput),f=this._dialogInst=this._newInst(this._dialogInput,!1),f.settings={},$.data(this._dialogInput[0],PROP_NAME,f)}extendRemove(f.settings,d||{}),b=b&&b.constructor==Date?this._formatDate(f,b):b,this._dialogInput.val(b),this._pos=e?e.length?e:[e.pageX,e.pageY]:null;if(!this._pos){var h=document.documentElement.clientWidth,i=document.documentElement.clientHeight,j=document.documentElement.scrollLeft||document.body.scrollLeft,k=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[h/2-100+j,i/2-150+k]}return this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px"),f.settings.onSelect=c,this._inDialog=!0,this.dpDiv.addClass(this._dialogClass),this._showDatepicker(this._dialogInput[0]),$.blockUI&&$.blockUI(this.dpDiv),$.data(this._dialogInput[0],PROP_NAME,f),this},_destroyDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!b.hasClass(this.markerClassName))return;var d=a.nodeName.toLowerCase();$.removeData(a,PROP_NAME),d=="input"?(c.append.remove(),c.trigger.remove(),b.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):(d=="div"||d=="span")&&b.removeClass(this.markerClassName).empty()},_enableDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!b.hasClass(this.markerClassName))return;var d=a.nodeName.toLowerCase();if(d=="input")a.disabled=!1,c.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""});else if(d=="div"||d=="span"){var e=b.children("."+this._inlineClass);e.children().removeClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").removeAttr("disabled")}this._disabledInputs=$.map(this._disabledInputs,function(b){return b==a?null:b})},_disableDatepicker:function(a){var b=$(a),c=$.data(a,PROP_NAME);if(!b.hasClass(this.markerClassName))return;var d=a.nodeName.toLowerCase();if(d=="input")a.disabled=!0,c.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"});else if(d=="div"||d=="span"){var e=b.children("."+this._inlineClass);e.children().addClass("ui-state-disabled"),e.find("select.ui-datepicker-month, select.ui-datepicker-year").attr("disabled","disabled")}this._disabledInputs=$.map(this._disabledInputs,function(b){return b==a?null:b}),this._disabledInputs[this._disabledInputs.length]=a},_isDisabledDatepicker:function(a){if(!a)return!1;for(var b=0;b<this._disabledInputs.length;b++)if(this._disabledInputs[b]==a)return!0;return!1},_getInst:function(a){try{return $.data(a,PROP_NAME)}catch(b){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(a,b,c){var d=this._getInst(a);if(arguments.length==2&&typeof b=="string")return b=="defaults"?$.extend({},$.datepicker._defaults):d?b=="all"?$.extend({},d.settings):this._get(d,b):null;var e=b||{};typeof b=="string"&&(e={},e[b]=c);if(d){this._curInst==d&&this._hideDatepicker();var f=this._getDateDatepicker(a,!0),g=this._getMinMaxDate(d,"min"),h=this._getMinMaxDate(d,"max");extendRemove(d.settings,e),g!==null&&e.dateFormat!==undefined&&e.minDate===undefined&&(d.settings.minDate=this._formatDate(d,g)),h!==null&&e.dateFormat!==undefined&&e.maxDate===undefined&&(d.settings.maxDate=this._formatDate(d,h)),this._attachments($(a),d),this._autoSize(d),this._setDate(d,f),this._updateAlternate(d),this._updateDatepicker(d)}},_changeDatepicker:function(a,b,c){this._optionDatepicker(a,b,c)},_refreshDatepicker:function(a){var b=this._getInst(a);b&&this._updateDatepicker(b)},_setDateDatepicker:function(a,b){var c=this._getInst(a);c&&(this._setDate(c,b),this._updateDatepicker(c),this._updateAlternate(c))},_getDateDatepicker:function(a,b){var c=this._getInst(a);return c&&!c.inline&&this._setDateFromField(c,b),c?this._getDate(c):null},_doKeyDown:function(a){var b=$.datepicker._getInst(a.target),c=!0,d=b.dpDiv.is(".ui-datepicker-rtl");b._keyEvent=!0;if($.datepicker._datepickerShowing)switch(a.keyCode){case 9:$.datepicker._hideDatepicker(),c=!1;break;case 13:var e=$("td."+$.datepicker._dayOverClass+":not(."+$.datepicker._currentClass+")",b.dpDiv);e[0]&&$.datepicker._selectDay(a.target,b.selectedMonth,b.selectedYear,e[0]);var f=$.datepicker._get(b,"onSelect");if(f){var g=$.datepicker._formatDate(b);f.apply(b.input?b.input[0]:null,[g,b])}else $.datepicker._hideDatepicker();return!1;case 27:$.datepicker._hideDatepicker();break;case 33:$.datepicker._adjustDate(a.target,a.ctrlKey?-$.datepicker._get(b,"stepBigMonths"):-$.datepicker._get(b,"stepMonths"),"M");break;case 34:$.datepicker._adjustDate(a.target,a.ctrlKey?+$.datepicker._get(b,"stepBigMonths"):+$.datepicker._get(b,"stepMonths"),"M");break;case 35:(a.ctrlKey||a.metaKey)&&$.datepicker._clearDate(a.target),c=a.ctrlKey||a.metaKey;break;case 36:(a.ctrlKey||a.metaKey)&&$.datepicker._gotoToday(a.target),c=a.ctrlKey||a.metaKey;break;case 37:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,d?1:-1,"D"),c=a.ctrlKey||a.metaKey,a.originalEvent.altKey&&$.datepicker._adjustDate(a.target,a.ctrlKey?-$.datepicker._get(b,"stepBigMonths"):-$.datepicker._get(b,"stepMonths"),"M");break;case 38:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,-7,"D"),c=a.ctrlKey||a.metaKey;break;case 39:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,d?-1:1,"D"),c=a.ctrlKey||a.metaKey,a.originalEvent.altKey&&$.datepicker._adjustDate(a.target,a.ctrlKey?+$.datepicker._get(b,"stepBigMonths"):+$.datepicker._get(b,"stepMonths"),"M");break;case 40:(a.ctrlKey||a.metaKey)&&$.datepicker._adjustDate(a.target,7,"D"),c=a.ctrlKey||a.metaKey;break;default:c=!1}else a.keyCode==36&&a.ctrlKey?$.datepicker._showDatepicker(this):c=!1;c&&(a.preventDefault(),a.stopPropagation())},_doKeyPress:function(a){var b=$.datepicker._getInst(a.target);if($.datepicker._get(b,"constrainInput")){var c=$.datepicker._possibleChars($.datepicker._get(b,"dateFormat")),d=String.fromCharCode(a.charCode==undefined?a.keyCode:a.charCode);return a.ctrlKey||a.metaKey||d<" "||!c||c.indexOf(d)>-1}},_doKeyUp:function(a){var b=$.datepicker._getInst(a.target);if(b.input.val()!=b.lastVal)try{var c=$.datepicker.parseDate($.datepicker._get(b,"dateFormat"),b.input?b.input.val():null,$.datepicker._getFormatConfig(b));c&&($.datepicker._setDateFromField(b),$.datepicker._updateAlternate(b),$.datepicker._updateDatepicker(b))}catch(d){$.datepicker.log(d)}return!0},_showDatepicker:function(a){a=a.target||a,a.nodeName.toLowerCase()!="input"&&(a=$("input",a.parentNode)[0]);if($.datepicker._isDisabledDatepicker(a)||$.datepicker._lastInput==a)return;var b=$.datepicker._getInst(a);$.datepicker._curInst&&$.datepicker._curInst!=b&&($.datepicker._curInst.dpDiv.stop(!0,!0),b&&$.datepicker._datepickerShowing&&$.datepicker._hideDatepicker($.datepicker._curInst.input[0]));var c=$.datepicker._get(b,"beforeShow"),d=c?c.apply(a,[a,b]):{};if(d===!1)return;extendRemove(b.settings,d),b.lastVal=null,$.datepicker._lastInput=a,$.datepicker._setDateFromField(b),$.datepicker._inDialog&&(a.value=""),$.datepicker._pos||($.datepicker._pos=$.datepicker._findPos(a),$.datepicker._pos[1]+=a.offsetHeight);var e=!1;$(a).parents().each(function(){return e|=$(this).css("position")=="fixed",!e}),e&&$.browser.opera&&($.datepicker._pos[0]-=document.documentElement.scrollLeft,$.datepicker._pos[1]-=document.documentElement.scrollTop);var f={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null,b.dpDiv.empty(),b.dpDiv.css({position:"absolute",display:"block",top:"-1000px"}),$.datepicker._updateDatepicker(b),f=$.datepicker._checkOffset(b,f,e),b.dpDiv.css({position:$.datepicker._inDialog&&$.blockUI?"static":e?"fixed":"absolute",display:"none",left:f.left+"px",top:f.top+"px"});if(!b.inline){var g=$.datepicker._get(b,"showAnim"),h=$.datepicker._get(b,"duration"),i=function(){var a=b.dpDiv.find("iframe.ui-datepicker-cover");if(!!a.length){var c=$.datepicker._getBorders(b.dpDiv);a.css({left:-c[0],top:-c[1],width:b.dpDiv.outerWidth(),height:b.dpDiv.outerHeight()})}};b.dpDiv.zIndex($(a).zIndex()+1),$.datepicker._datepickerShowing=!0,$.effects&&$.effects[g]?b.dpDiv.show(g,$.datepicker._get(b,"showOptions"),h,i):b.dpDiv[g||"show"](g?h:null,i),(!g||!h)&&i(),b.input.is(":visible")&&!b.input.is(":disabled")&&b.input.focus(),$.datepicker._curInst=b}},_updateDatepicker:function(a){var b=this;b.maxRows=4;var c=$.datepicker._getBorders(a.dpDiv);instActive=a,a.dpDiv.empty().append(this._generateHTML(a));var d=a.dpDiv.find("iframe.ui-datepicker-cover");!d.length||d.css({left:-c[0],top:-c[1],width:a.dpDiv.outerWidth(),height:a.dpDiv.outerHeight()}),a.dpDiv.find("."+this._dayOverClass+" a").mouseover();var e=this._getNumberOfMonths(a),f=e[1],g=17;a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width(""),f>1&&a.dpDiv.addClass("ui-datepicker-multi-"+f).css("width",g*f+"em"),a.dpDiv[(e[0]!=1||e[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi"),a.dpDiv[(this._get(a,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl"),a==$.datepicker._curInst&&$.datepicker._datepickerShowing&&a.input&&a.input.is(":visible")&&!a.input.is(":disabled")&&a.input[0]!=document.activeElement&&a.input.focus();if(a.yearshtml){var h=a.yearshtml;setTimeout(function(){h===a.yearshtml&&a.yearshtml&&a.dpDiv.find("select.ui-datepicker-year:first").replaceWith(a.yearshtml),h=a.yearshtml=null},0)}},_getBorders:function(a){var b=function(a){return{thin:1,medium:2,thick:3}[a]||a};return[parseFloat(b(a.css("border-left-width"))),parseFloat(b(a.css("border-top-width")))]},_checkOffset:function(a,b,c){var d=a.dpDiv.outerWidth(),e=a.dpDiv.outerHeight(),f=a.input?a.input.outerWidth():0,g=a.input?a.input.outerHeight():0,h=document.documentElement.clientWidth+$(document).scrollLeft(),i=document.documentElement.clientHeight+$(document).scrollTop();return b.left-=this._get(a,"isRTL")?d-f:0,b.left-=c&&b.left==a.input.offset().left?$(document).scrollLeft():0,b.top-=c&&b.top==a.input.offset().top+g?$(document).scrollTop():0,b.left-=Math.min(b.left,b.left+d>h&&h>d?Math.abs(b.left+d-h):0),b.top-=Math.min(b.top,b.top+e>i&&i>e?Math.abs(e+g):0),b},_findPos:function(a){var b=this._getInst(a),c=this._get(b,"isRTL");while(a&&(a.type=="hidden"||a.nodeType!=1||$.expr.filters.hidden(a)))a=a[c?"previousSibling":"nextSibling"];var d=$(a).offset();return[d.left,d.top]},_hideDatepicker:function(a){var b=this._curInst;if(!b||a&&b!=$.data(a,PROP_NAME))return;if(this._datepickerShowing){var c=this._get(b,"showAnim"),d=this._get(b,"duration"),e=function(){$.datepicker._tidyDialog(b)};$.effects&&$.effects[c]?b.dpDiv.hide(c,$.datepicker._get(b,"showOptions"),d,e):b.dpDiv[c=="slideDown"?"slideUp":c=="fadeIn"?"fadeOut":"hide"](c?d:null,e),c||e(),this._datepickerShowing=!1;var f=this._get(b,"onClose");f&&f.apply(b.input?b.input[0]:null,[b.input?b.input.val():"",b]),this._lastInput=null,this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),$.blockUI&&($.unblockUI(),$("body").append(this.dpDiv))),this._inDialog=!1}},_tidyDialog:function(a){a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(a){if(!$.datepicker._curInst)return;var b=$(a.target),c=$.datepicker._getInst(b[0]);(b[0].id!=$.datepicker._mainDivId&&b.parents("#"+$.datepicker._mainDivId).length==0&&!b.hasClass($.datepicker.markerClassName)&&!b.closest("."+$.datepicker._triggerClass).length&&$.datepicker._datepickerShowing&&(!$.datepicker._inDialog||!$.blockUI)||b.hasClass($.datepicker.markerClassName)&&$.datepicker._curInst!=c)&&$.datepicker._hideDatepicker()},_adjustDate:function(a,b,c){var d=$(a),e=this._getInst(d[0]);if(this._isDisabledDatepicker(d[0]))return;this._adjustInstDate(e,b+(c=="M"?this._get(e,"showCurrentAtPos"):0),c),this._updateDatepicker(e)},_gotoToday:function(a){var b=$(a),c=this._getInst(b[0]);if(this._get(c,"gotoCurrent")&&c.currentDay)c.selectedDay=c.currentDay,c.drawMonth=c.selectedMonth=c.currentMonth,c.drawYear=c.selectedYear=c.currentYear;else{var d=new Date;c.selectedDay=d.getDate(),c.drawMonth=c.selectedMonth=d.getMonth(),c.drawYear=c.selectedYear=d.getFullYear()}this._notifyChange(c),this._adjustDate(b)},_selectMonthYear:function(a,b,c){var d=$(a),e=this._getInst(d[0]);e["selected"+(c=="M"?"Month":"Year")]=e["draw"+(c=="M"?"Month":"Year")]=parseInt(b.options[b.selectedIndex].value,10),this._notifyChange(e),this._adjustDate(d)},_selectDay:function(a,b,c,d){var e=$(a);if($(d).hasClass(this._unselectableClass)||this._isDisabledDatepicker(e[0]))return;var f=this._getInst(e[0]);f.selectedDay=f.currentDay=$("a",d).html(),f.selectedMonth=f.currentMonth=b,f.selectedYear=f.currentYear=c,this._selectDate(a,this._formatDate(f,f.currentDay,f.currentMonth,f.currentYear))},_clearDate:function(a){var b=$(a),c=this._getInst(b[0]);this._selectDate(b,"")},_selectDate:function(a,b){var c=$(a),d=this._getInst(c[0]);b=b!=null?b:this._formatDate(d),d.input&&d.input.val(b),this._updateAlternate(d);var e=this._get(d,"onSelect");e?e.apply(d.input?d.input[0]:null,[b,d]):d.input&&d.input.trigger("change"),d.inline?this._updateDatepicker(d):(this._hideDatepicker(),this._lastInput=d.input[0],typeof d.input[0]!="object"&&d.input.focus(),this._lastInput=null)},_updateAlternate:function(a){var b=this._get(a,"altField");if(b){var c=this._get(a,"altFormat")||this._get(a,"dateFormat"),d=this._getDate(a),e=this.formatDate(c,d,this._getFormatConfig(a));$(b).each(function(){$(this).val(e)})}},noWeekends:function(a){var b=a.getDay();return[b>0&&b<6,""]},iso8601Week:function(a){var b=new Date(a.getTime());b.setDate(b.getDate()+4-(b.getDay()||7));var c=b.getTime();return b.setMonth(0),b.setDate(1),Math.floor(Math.round((c-b)/864e5)/7)+1},parseDate:function(a,b,c){if(a==null||b==null)throw"Invalid arguments";b=typeof b=="object"?b.toString():b+"";if(b=="")return null;var d=(c?c.shortYearCutoff:null)||this._defaults.shortYearCutoff;d=typeof d!="string"?d:(new Date).getFullYear()%100+parseInt(d,10);var e=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,f=(c?c.dayNames:null)||this._defaults.dayNames,g=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,h=(c?c.monthNames:null)||this._defaults.monthNames,i=-1,j=-1,k=-1,l=-1,m=!1,n=function(b){var c=s+1<a.length&&a.charAt(s+1)==b;return c&&s++,c},o=function(a){var c=n(a),d=a=="@"?14:a=="!"?20:a=="y"&&c?4:a=="o"?3:2,e=new RegExp("^\\d{1,"+d+"}"),f=b.substring(r).match(e);if(!f)throw"Missing number at position "+r;return r+=f[0].length,parseInt(f[0],10)},p=function(a,c,d){var e=$.map(n(a)?d:c,function(a,b){return[[b,a]]}).sort(function(a,b){return-(a[1].length-b[1].length)}),f=-1;$.each(e,function(a,c){var d=c[1];if(b.substr(r,d.length).toLowerCase()==d.toLowerCase())return f=c[0],r+=d.length,!1});if(f!=-1)return f+1;throw"Unknown name at position "+r},q=function(){if(b.charAt(r)!=a.charAt(s))throw"Unexpected literal at position "+r;r++},r=0;for(var s=0;s<a.length;s++)if(m)a.charAt(s)=="'"&&!n("'")?m=!1:q();else switch(a.charAt(s)){case"d":k=o("d");break;case"D":p("D",e,f);break;case"o":l=o("o");break;case"m":j=o("m");break;case"M":j=p("M",g,h);break;case"y":i=o("y");break;case"@":var t=new Date(o("@"));i=t.getFullYear(),j=t.getMonth()+1,k=t.getDate();break;case"!":var t=new Date((o("!")-this._ticksTo1970)/1e4);i=t.getFullYear(),j=t.getMonth()+1,k=t.getDate();break;case"'":n("'")?q():m=!0;break;default:q()}if(r<b.length)throw"Extra/unparsed characters found in date: "+b.substring(r);i==-1?i=(new Date).getFullYear():i<100&&(i+=(new Date).getFullYear()-(new Date).getFullYear()%100+(i<=d?0:-100));if(l>-1){j=1,k=l;do{var u=this._getDaysInMonth(i,j-1);if(k<=u)break;j++,k-=u}while(!0)}var t=this._daylightSavingAdjust(new Date(i,j-1,k));if(t.getFullYear()!=i||t.getMonth()+1!=j||t.getDate()!=k)throw"Invalid date";return t},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*24*60*60*1e7,formatDate:function(a,b,c){if(!b)return"";var d=(c?c.dayNamesShort:null)||this._defaults.dayNamesShort,e=(c?c.dayNames:null)||this._defaults.dayNames,f=(c?c.monthNamesShort:null)||this._defaults.monthNamesShort,g=(c?c.monthNames:null)||this._defaults.monthNames,h=function(b){var c=m+1<a.length&&a.charAt(m+1)==b;return c&&m++,c},i=function(a,b,c){var d=""+b;if(h(a))while(d.length<c)d="0"+d;return d},j=function(a,b,c,d){return h(a)?d[b]:c[b]},k="",l=!1;if(b)for(var m=0;m<a.length;m++)if(l)a.charAt(m)=="'"&&!h("'")?l=!1:k+=a.charAt(m);else switch(a.charAt(m)){case"d":k+=i("d",b.getDate(),2);break;case"D":k+=j("D",b.getDay(),d,e);break;case"o":k+=i("o",Math.round(((new Date(b.getFullYear(),b.getMonth(),b.getDate())).getTime()-(new Date(b.getFullYear(),0,0)).getTime())/864e5),3);break;case"m":k+=i("m",b.getMonth()+1,2);break;case"M":k+=j("M",b.getMonth(),f,g);break;case"y":k+=h("y")?b.getFullYear():(b.getYear()%100<10?"0":"")+b.getYear()%100;break;case"@":k+=b.getTime();break;case"!":k+=b.getTime()*1e4+this._ticksTo1970;break;case"'":h("'")?k+="'":l=!0;break;default:k+=a.charAt(m)}return k},_possibleChars:function(a){var b="",c=!1,d=function(b){var c=e+1<a.length&&a.charAt(e+1)==b;return c&&e++,c};for(var e=0;e<a.length;e++)if(c)a.charAt(e)=="'"&&!d("'")?c=!1:b+=a.charAt(e);else switch(a.charAt(e)){case"d":case"m":case"y":case"@":b+="0123456789";break;case"D":case"M":return null;case"'":d("'")?b+="'":c=!0;break;default:b+=a.charAt(e)}return b},_get:function(a,b){return a.settings[b]!==undefined?a.settings[b]:this._defaults[b]},_setDateFromField:function(a,b){if(a.input.val()==a.lastVal)return;var c=this._get(a,"dateFormat"),d=a.lastVal=a.input?a.input.val():null,e,f;e=f=this._getDefaultDate(a);var g=this._getFormatConfig(a);try{e=this.parseDate(c,d,g)||f}catch(h){this.log(h),d=b?"":d}a.selectedDay=e.getDate(),a.drawMonth=a.selectedMonth=e.getMonth(),a.drawYear=a.selectedYear=e.getFullYear(),a.currentDay=d?e.getDate():0,a.currentMonth=d?e.getMonth():0,a.currentYear=d?e.getFullYear():0,this._adjustInstDate(a)},_getDefaultDate:function(a){return this._restrictMinMax(a,this._determineDate(a,this._get(a,"defaultDate"),new Date))},_determineDate:function(a,b,c){var d=function(a){var b=new Date;return b.setDate(b.getDate()+a),b},e=function(b){try{return $.datepicker.parseDate($.datepicker._get(a,"dateFormat"),b,$.datepicker._getFormatConfig(a))}catch(c){}var d=(b.toLowerCase().match(/^c/)?$.datepicker._getDate(a):null)||new Date,e=d.getFullYear(),f=d.getMonth(),g=d.getDate(),h=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,i=h.exec(b);while(i){switch(i[2]||"d"){case"d":case"D":g+=parseInt(i[1],10);break;case"w":case"W":g+=parseInt(i[1],10)*7;break;case"m":case"M":f+=parseInt(i[1],10),g=Math.min(g,$.datepicker._getDaysInMonth(e,f));break;case"y":case"Y":e+=parseInt(i[1],10),g=Math.min(g,$.datepicker._getDaysInMonth(e,f))}i=h.exec(b)}return new Date(e,f,g)},f=b==null||b===""?c:typeof b=="string"?e(b):typeof b=="number"?isNaN(b)?c:d(b):new Date(b.getTime());return f=f&&f.toString()=="Invalid Date"?c:f,f&&(f.setHours(0),f.setMinutes(0),f.setSeconds(0),f.setMilliseconds(0)),this._daylightSavingAdjust(f)},_daylightSavingAdjust:function(a){return a?(a.setHours(a.getHours()>12?a.getHours()+2:0),a):null},_setDate:function(a,b,c){var d=!b,e=a.selectedMonth,f=a.selectedYear,g=this._restrictMinMax(a,this._determineDate(a,b,new Date));a.selectedDay=a.currentDay=g.getDate(),a.drawMonth=a.selectedMonth=a.currentMonth=g.getMonth(),a.drawYear=a.selectedYear=a.currentYear=g.getFullYear(),(e!=a.selectedMonth||f!=a.selectedYear)&&!c&&this._notifyChange(a),this._adjustInstDate(a),a.input&&a.input.val(d?"":this._formatDate(a))},_getDate:function(a){var b=!a.currentYear||a.input&&a.input.val()==""?null:this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return b},_generateHTML:function(a){var b=new Date;b=this._daylightSavingAdjust(new Date(b.getFullYear(),b.getMonth(),b.getDate()));var c=this._get(a,"isRTL"),d=this._get(a,"showButtonPanel"),e=this._get(a,"hideIfNoPrevNext"),f=this._get(a,"navigationAsDateFormat"),g=this._getNumberOfMonths(a),h=this._get(a,"showCurrentAtPos"),i=this._get(a,"stepMonths"),j=g[0]!=1||g[1]!=1,k=this._daylightSavingAdjust(a.currentDay?new Date(a.currentYear,a.currentMonth,a.currentDay):new Date(9999,9,9)),l=this._getMinMaxDate(a,"min"),m=this._getMinMaxDate(a,"max"),n=a.drawMonth-h,o=a.drawYear;n<0&&(n+=12,o--);if(m){var p=this._daylightSavingAdjust(new Date(m.getFullYear(),m.getMonth()-g[0]*g[1]+1,m.getDate()));p=l&&p<l?l:p;while(this._daylightSavingAdjust(new Date(o,n,1))>p)n--,n<0&&(n=11,o--)}a.drawMonth=n,a.drawYear=o;var q=this._get(a,"prevText");q=f?this.formatDate(q,this._daylightSavingAdjust(new Date(o,n-i,1)),this._getFormatConfig(a)):q;var r=this._canAdjustMonth(a,-1,o,n)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._adjustDate('#"+a.id+"', -"+i+", 'M');\""+' title="'+q+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+q+"</span></a>":e?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+q+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"e":"w")+'">'+q+"</span></a>",s=this._get(a,"nextText");s=f?this.formatDate(s,this._daylightSavingAdjust(new Date(o,n+i,1)),this._getFormatConfig(a)):s;var t=this._canAdjustMonth(a,1,o,n)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._adjustDate('#"+a.id+"', +"+i+", 'M');\""+' title="'+s+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+s+"</span></a>":e?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+s+'"><span class="ui-icon ui-icon-circle-triangle-'+(c?"w":"e")+'">'+s+"</span></a>",u=this._get(a,"currentText"),v=this._get(a,"gotoCurrent")&&a.currentDay?k:b;u=f?this.formatDate(u,v,this._getFormatConfig(a)):u;var w=a.inline?"":'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_'+dpuuid+'.datepicker._hideDatepicker();">'+this._get(a,"closeText")+"</button>",x=d?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(c?w:"")+(this._isInRange(a,v)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_'+dpuuid+".datepicker._gotoToday('#"+a.id+"');\""+">"+u+"</button>":"")+(c?"":w)+"</div>":"",y=parseInt(this._get(a,"firstDay"),10);y=isNaN(y)?0:y;var z=this._get(a,"showWeek"),A=this._get(a,"dayNames"),B=this._get(a,"dayNamesShort"),C=this._get(a,"dayNamesMin"),D=this._get(a,"monthNames"),E=this._get(a,"monthNamesShort"),F=this._get(a,"beforeShowDay"),G=this._get(a,"showOtherMonths"),H=this._get(a,"selectOtherMonths"),I=this._get(a,"calculateWeek")||this.iso8601Week,J=this._getDefaultDate(a),K="";for(var L=0;L<g[0];L++){var M="";this.maxRows=4;for(var N=0;N<g[1];N++){var O=this._daylightSavingAdjust(new Date(o,n,a.selectedDay)),P=" ui-corner-all",Q="";if(j){Q+='<div class="ui-datepicker-group';if(g[1]>1)switch(N){case 0:Q+=" ui-datepicker-group-first",P=" ui-corner-"+(c?"right":"left");break;case g[1]-1:Q+=" ui-datepicker-group-last",P=" ui-corner-"+(c?"left":"right");break;default:Q+=" ui-datepicker-group-middle",P=""}Q+='">'}Q+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+P+'">'+(/all|left/.test(P)&&L==0?c?t:r:"")+(/all|right/.test(P)&&L==0?c?r:t:"")+this._generateMonthYearHeader(a,n,o,l,m,L>0||N>0,D,E)+'</div><table class="ui-datepicker-calendar"><thead>'+"<tr>";var R=z?'<th class="ui-datepicker-week-col">'+this._get(a,"weekHeader")+"</th>":"";for(var S=0;S<7;S++){var T=(S+y)%7;R+="<th"+((S+y+6)%7>=5?' class="ui-datepicker-week-end"':"")+">"+'<span title="'+A[T]+'">'+C[T]+"</span></th>"}Q+=R+"</tr></thead><tbody>";var U=this._getDaysInMonth(o,n);o==a.selectedYear&&n==a.selectedMonth&&(a.selectedDay=Math.min(a.selectedDay,U));var V=(this._getFirstDayOfMonth(o,n)-y+7)%7,W=Math.ceil((V+U)/7),X=j?this.maxRows>W?this.maxRows:W:W;this.maxRows=X;var Y=this._daylightSavingAdjust(new Date(o,n,1-V));for(var Z=0;Z<X;Z++){Q+="<tr>";var _=z?'<td class="ui-datepicker-week-col">'+this._get(a,"calculateWeek")(Y)+"</td>":"";for(var S=0;S<7;S++){var ba=F?F.apply(a.input?a.input[0]:null,[Y]):[!0,""],bb=Y.getMonth()!=n,bc=bb&&!H||!ba[0]||l&&Y<l||m&&Y>m;_+='<td class="'+((S+y+6)%7>=5?" ui-datepicker-week-end":"")+(bb?" ui-datepicker-other-month":"")+(Y.getTime()==O.getTime()&&n==a.selectedMonth&&a._keyEvent||J.getTime()==Y.getTime()&&J.getTime()==O.getTime()?" "+this._dayOverClass:"")+(bc?" "+this._unselectableClass+" ui-state-disabled":"")+(bb&&!G?"":" "+ba[1]+(Y.getTime()==k.getTime()?" "+this._currentClass:"")+(Y.getTime()==b.getTime()?" ui-datepicker-today":""))+'"'+((!bb||G)&&ba[2]?' title="'+ba[2]+'"':"")+(bc?"":' onclick="DP_jQuery_'+dpuuid+".datepicker._selectDay('#"+a.id+"',"+Y.getMonth()+","+Y.getFullYear()+', this);return false;"')+">"+(bb&&!G?" ":bc?'<span class="ui-state-default">'+Y.getDate()+"</span>":'<a class="ui-state-default'+(Y.getTime()==b.getTime()?" ui-state-highlight":"")+(Y.getTime()==k.getTime()?" ui-state-active":"")+(bb?" ui-priority-secondary":"")+'" href="#">'+Y.getDate()+"</a>")+"</td>",Y.setDate(Y.getDate()+1),Y=this._daylightSavingAdjust(Y)}Q+=_+"</tr>"}n++,n>11&&(n=0,o++),Q+="</tbody></table>"+(j?"</div>"+(g[0]>0&&N==g[1]-1?'<div class="ui-datepicker-row-break"></div>':""):""),M+=Q}K+=M}return K+=x+($.browser.msie&&parseInt($.browser.version,10)<7&&!a.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':""),a._keyEvent=!1,K},_generateMonthYearHeader:function(a,b,c,d,e,f,g,h){var i=this._get(a,"changeMonth"),j=this._get(a,"changeYear"),k=this._get(a,"showMonthAfterYear"),l='<div class="ui-datepicker-title">',m="";if(f||!i)m+='<span class="ui-datepicker-month">'+g[b]+"</span>";else{var n=d&&d.getFullYear()==c,o=e&&e.getFullYear()==c;m+='<select class="ui-datepicker-month" onchange="DP_jQuery_'+dpuuid+".datepicker._selectMonthYear('#"+a.id+"', this, 'M');\" "+">";for(var p=0;p<12;p++)(!n||p>=d.getMonth())&&(!o||p<=e.getMonth())&&(m+='<option value="'+p+'"'+(p==b?' selected="selected"':"")+">"+h[p]+"</option>");m+="</select>"}k||(l+=m+(f||!i||!j?" ":""));if(!a.yearshtml){a.yearshtml="";if(f||!j)l+='<span class="ui-datepicker-year">'+c+"</span>";else{var q=this._get(a,"yearRange").split(":"),r=(new Date).getFullYear(),s=function(a){var b=a.match(/c[+-].*/)?c+parseInt(a.substring(1),10):a.match(/[+-].*/)?r+parseInt(a,10):parseInt(a,10);return isNaN(b)?r:b},t=s(q[0]),u=Math.max(t,s(q[1]||""));t=d?Math.max(t,d.getFullYear()):t,u=e?Math.min(u,e.getFullYear()):u,a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+dpuuid+".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');\" "+">";for(;t<=u;t++)a.yearshtml+='<option value="'+t+'"'+(t==c?' selected="selected"':"")+">"+t+"</option>";a.yearshtml+="</select>",l+=a.yearshtml,a.yearshtml=null}}return l+=this._get(a,"yearSuffix"),k&&(l+=(f||!i||!j?" ":"")+m),l+="</div>",l},_adjustInstDate:function(a,b,c){var d=a.drawYear+(c=="Y"?b:0),e=a.drawMonth+(c=="M"?b:0),f=Math.min(a.selectedDay,this._getDaysInMonth(d,e))+(c=="D"?b:0),g=this._restrictMinMax(a,this._daylightSavingAdjust(new Date(d,e,f)));a.selectedDay=g.getDate(),a.drawMonth=a.selectedMonth=g.getMonth(),a.drawYear=a.selectedYear=g.getFullYear(),(c=="M"||c=="Y")&&this._notifyChange(a)},_restrictMinMax:function(a,b){var c=this._getMinMaxDate(a,"min"),d=this._getMinMaxDate(a,"max"),e=c&&b<c?c:b;return e=d&&e>d?d:e,e},_notifyChange:function(a){var b=this._get(a,"onChangeMonthYear");b&&b.apply(a.input?a.input[0]:null,[a.selectedYear,a.selectedMonth+1,a])},_getNumberOfMonths:function(a){var b=this._get(a,"numberOfMonths");return b==null?[1,1]:typeof b=="number"?[1,b]:b},_getMinMaxDate:function(a,b){return this._determineDate(a,this._get(a,b+"Date"),null)},_getDaysInMonth:function(a,b){return 32-this._daylightSavingAdjust(new Date(a,b,32)).getDate()},_getFirstDayOfMonth:function(a,b){return(new Date(a,b,1)).getDay()},_canAdjustMonth:function(a,b,c,d){var e=this._getNumberOfMonths(a),f=this._daylightSavingAdjust(new Date(c,d+(b<0?b:e[0]*e[1]),1));return b<0&&f.setDate(this._getDaysInMonth(f.getFullYear(),f.getMonth())),this._isInRange(a,f)},_isInRange:function(a,b){var c=this._getMinMaxDate(a,"min"),d=this._getMinMaxDate(a,"max");return(!c||b.getTime()>=c.getTime())&&(!d||b.getTime()<=d.getTime())},_getFormatConfig:function(a){var b=this._get(a,"shortYearCutoff");return b=typeof b!="string"?b:(new Date).getFullYear()%100+parseInt(b,10),{shortYearCutoff:b,dayNamesShort:this._get(a,"dayNamesShort"),dayNames:this._get(a,"dayNames"),monthNamesShort:this._get(a,"monthNamesShort"),monthNames:this._get(a,"monthNames")}},_formatDate:function(a,b,c,d){b||(a.currentDay=a.selectedDay,a.currentMonth=a.selectedMonth,a.currentYear=a.selectedYear);var e=b?typeof b=="object"?b:this._daylightSavingAdjust(new Date(d,c,b)):this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return this.formatDate(this._get(a,"dateFormat"),e,this._getFormatConfig(a))}}),$.fn.datepicker=function(a){if(!this.length)return this;$.datepicker.initialized||($(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv),$.datepicker.initialized=!0);var b=Array.prototype.slice.call(arguments,1);return typeof a!="string"||a!="isDisabled"&&a!="getDate"&&a!="widget"?a=="option"&&arguments.length==2&&typeof arguments[1]=="string"?$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this[0]].concat(b)):this.each(function(){typeof a=="string"?$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this].concat(b)):$.datepicker._attachDatepicker(this,a)}):$.datepicker["_"+a+"Datepicker"].apply($.datepicker,[this[0]].concat(b))},$.datepicker=new Datepicker,$.datepicker.initialized=!1,$.datepicker.uuid=(new Date).getTime(),$.datepicker.version="1.8.21",window["DP_jQuery_"+dpuuid]=$})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1565 * https://github.com/jquery/jquery-ui
1566 * Includes: jquery.ui.progressbar.js
1567 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1568 (function(a,b){a.widget("ui.progressbar",{options:{value:0,max:100},min:0,_create:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min,"aria-valuemax":this.options.max,"aria-valuenow":this._value()}),this.valueDiv=a("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element),this.oldValue=this._value(),this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow"),this.valueDiv.remove(),a.Widget.prototype.destroy.apply(this,arguments)},value:function(a){return a===b?this._value():(this._setOption("value",a),this)},_setOption:function(b,c){b==="value"&&(this.options.value=c,this._refreshValue(),this._value()===this.options.max&&this._trigger("complete")),a.Widget.prototype._setOption.apply(this,arguments)},_value:function(){var a=this.options.value;return typeof a!="number"&&(a=0),Math.min(this.options.max,Math.max(this.min,a))},_percentage:function(){return 100*this._value()/this.options.max},_refreshValue:function(){var a=this.value(),b=this._percentage();this.oldValue!==a&&(this.oldValue=a,this._trigger("change")),this.valueDiv.toggle(a>this.min).toggleClass("ui-corner-right",a===this.options.max).width(b.toFixed(0)+"%"),this.element.attr("aria-valuenow",a)}}),a.extend(a.ui.progressbar,{version:"1.8.21"})})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1569 * https://github.com/jquery/jquery-ui
1570 * Includes: jquery.effects.core.js
1571 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1572 jQuery.effects||function(a,b){function c(b){var c;return b&&b.constructor==Array&&b.length==3?b:(c=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(b))?[parseInt(c[1],10),parseInt(c[2],10),parseInt(c[3],10)]:(c=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(b))?[parseFloat(c[1])*2.55,parseFloat(c[2])*2.55,parseFloat(c[3])*2.55]:(c=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(b))?[parseInt(c[1],16),parseInt(c[2],16),parseInt(c[3],16)]:(c=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(b))?[parseInt(c[1]+c[1],16),parseInt(c[2]+c[2],16),parseInt(c[3]+c[3],16)]:(c=/rgba\(0, 0, 0, 0\)/.exec(b))?e.transparent:e[a.trim(b).toLowerCase()]}function d(b,d){var e;do{e=a.curCSS(b,d);if(e!=""&&e!="transparent"||a.nodeName(b,"body"))break;d="backgroundColor"}while(b=b.parentNode);return c(e)}function h(){var a=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle,b={},c,d;if(a&&a.length&&a[0]&&a[a[0]]){var e=a.length;while(e--)c=a[e],typeof a[c]=="string"&&(d=c.replace(/\-(\w)/g,function(a,b){return b.toUpperCase()}),b[d]=a[c])}else for(c in a)typeof a[c]=="string"&&(b[c]=a[c]);return b}function i(b){var c,d;for(c in b)d=b[c],(d==null||a.isFunction(d)||c in g||/scrollbar/.test(c)||!/color/i.test(c)&&isNaN(parseFloat(d)))&&delete b[c];return b}function j(a,b){var c={_:0},d;for(d in b)a[d]!=b[d]&&(c[d]=b[d]);return c}function k(b,c,d,e){typeof b=="object"&&(e=c,d=null,c=b,b=c.effect),a.isFunction(c)&&(e=c,d=null,c={});if(typeof c=="number"||a.fx.speeds[c])e=d,d=c,c={};return a.isFunction(d)&&(e=d,d=null),c=c||{},d=d||c.duration,d=a.fx.off?0:typeof d=="number"?d:d in a.fx.speeds?a.fx.speeds[d]:a.fx.speeds._default,e=e||c.complete,[b,c,d,e]}function l(b){return!b||typeof b=="number"||a.fx.speeds[b]?!0:typeof b=="string"&&!a.effects[b]?!0:!1}a.effects={},a.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","borderColor","color","outlineColor"],function(b,e){a.fx.step[e]=function(a){a.colorInit||(a.start=d(a.elem,e),a.end=c(a.end),a.colorInit=!0),a.elem.style[e]="rgb("+Math.max(Math.min(parseInt(a.pos*(a.end[0]-a.start[0])+a.start[0],10),255),0)+","+Math.max(Math.min(parseInt(a.pos*(a.end[1]-a.start[1])+a.start[1],10),255),0)+","+Math.max(Math.min(parseInt(a.pos*(a.end[2]-a.start[2])+a.start[2],10),255),0)+")"}});var e={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},f=["add","remove","toggle"],g={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};a.effects.animateClass=function(b,c,d,e){return a.isFunction(d)&&(e=d,d=null),this.queue(function(){var g=a(this),k=g.attr("style")||" ",l=i(h.call(this)),m,n=g.attr("class")||"";a.each(f,function(a,c){b[c]&&g[c+"Class"](b[c])}),m=i(h.call(this)),g.attr("class",n),g.animate(j(l,m),{queue:!1,duration:c,easing:d,complete:function(){a.each(f,function(a,c){b[c]&&g[c+"Class"](b[c])}),typeof g.attr("style")=="object"?(g.attr("style").cssText="",g.attr("style").cssText=k):g.attr("style",k),e&&e.apply(this,arguments),a.dequeue(this)}})})},a.fn.extend({_addClass:a.fn.addClass,addClass:function(b,c,d,e){return c?a.effects.animateClass.apply(this,[{add:b},c,d,e]):this._addClass(b)},_removeClass:a.fn.removeClass,removeClass:function(b,c,d,e){return c?a.effects.animateClass.apply(this,[{remove:b},c,d,e]):this._removeClass(b)},_toggleClass:a.fn.toggleClass,toggleClass:function(c,d,e,f,g){return typeof d=="boolean"||d===b?e?a.effects.animateClass.apply(this,[d?{add:c}:{remove:c},e,f,g]):this._toggleClass(c,d):a.effects.animateClass.apply(this,[{toggle:c},d,e,f])},switchClass:function(b,c,d,e,f){return a.effects.animateClass.apply(this,[{add:c,remove:b},d,e,f])}}),a.extend(a.effects,{version:"1.8.21",save:function(a,b){for(var c=0;c<b.length;c++)b[c]!==null&&a.data("ec.storage."+b[c],a[0].style[b[c]])},restore:function(a,b){for(var c=0;c<b.length;c++)b[c]!==null&&a.css(b[c],a.data("ec.storage."+b[c]))},setMode:function(a,b){return b=="toggle"&&(b=a.is(":hidden")?"show":"hide"),b},getBaseline:function(a,b){var c,d;switch(a[0]){case"top":c=0;break;case"middle":c=.5;break;case"bottom":c=1;break;default:c=a[0]/b.height}switch(a[1]){case"left":d=0;break;case"center":d=.5;break;case"right":d=1;break;default:d=a[1]/b.width}return{x:d,y:c}},createWrapper:function(b){if(b.parent().is(".ui-effects-wrapper"))return b.parent();var c={width:b.outerWidth(!0),height:b.outerHeight(!0),"float":b.css("float")},d=a("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),e=document.activeElement;try{e.id}catch(f){e=document.body}return b.wrap(d),(b[0]===e||a.contains(b[0],e))&&a(e).focus(),d=b.parent(),b.css("position")=="static"?(d.css({position:"relative"}),b.css({position:"relative"})):(a.extend(c,{position:b.css("position"),zIndex:b.css("z-index")}),a.each(["top","left","bottom","right"],function(a,d){c[d]=b.css(d),isNaN(parseInt(c[d],10))&&(c[d]="auto")}),b.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})),d.css(c).show()},removeWrapper:function(b){var c,d=document.activeElement;return b.parent().is(".ui-effects-wrapper")?(c=b.parent().replaceWith(b),(b[0]===d||a.contains(b[0],d))&&a(d).focus(),c):b},setTransition:function(b,c,d,e){return e=e||{},a.each(c,function(a,c){var f=b.cssUnit(c);f[0]>0&&(e[c]=f[0]*d+f[1])}),e}}),a.fn.extend({effect:function(b,c,d,e){var f=k.apply(this,arguments),g={options:f[1],duration:f[2],callback:f[3]},h=g.options.mode,i=a.effects[b];return a.fx.off||!i?h?this[h](g.duration,g.callback):this.each(function(){g.callback&&g.callback.call(this)}):i.call(this,g)},_show:a.fn.show,show:function(a){if(l(a))return this._show.apply(this,arguments);var b=k.apply(this,arguments);return b[1].mode="show",this.effect.apply(this,b)},_hide:a.fn.hide,hide:function(a){if(l(a))return this._hide.apply(this,arguments);var b=k.apply(this,arguments);return b[1].mode="hide",this.effect.apply(this,b)},__toggle:a.fn.toggle,toggle:function(b){if(l(b)||typeof b=="boolean"||a.isFunction(b))return this.__toggle.apply(this,arguments);var c=k.apply(this,arguments);return c[1].mode="toggle",this.effect.apply(this,c)},cssUnit:function(b){var c=this.css(b),d=[];return a.each(["em","px","%","pt"],function(a,b){c.indexOf(b)>0&&(d=[parseFloat(c),b])}),d}}),a.easing.jswing=a.easing.swing,a.extend(a.easing,{def:"easeOutQuad",swing:function(b,c,d,e,f){return a.easing[a.easing.def](b,c,d,e,f)},easeInQuad:function(a,b,c,d,e){return d*(b/=e)*b+c},easeOutQuad:function(a,b,c,d,e){return-d*(b/=e)*(b-2)+c},easeInOutQuad:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b+c:-d/2*(--b*(b-2)-1)+c},easeInCubic:function(a,b,c,d,e){return d*(b/=e)*b*b+c},easeOutCubic:function(a,b,c,d,e){return d*((b=b/e-1)*b*b+1)+c},easeInOutCubic:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b*b+c:d/2*((b-=2)*b*b+2)+c},easeInQuart:function(a,b,c,d,e){return d*(b/=e)*b*b*b+c},easeOutQuart:function(a,b,c,d,e){return-d*((b=b/e-1)*b*b*b-1)+c},easeInOutQuart:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b*b*b+c:-d/2*((b-=2)*b*b*b-2)+c},easeInQuint:function(a,b,c,d,e){return d*(b/=e)*b*b*b*b+c},easeOutQuint:function(a,b,c,d,e){return d*((b=b/e-1)*b*b*b*b+1)+c},easeInOutQuint:function(a,b,c,d,e){return(b/=e/2)<1?d/2*b*b*b*b*b+c:d/2*((b-=2)*b*b*b*b+2)+c},easeInSine:function(a,b,c,d,e){return-d*Math.cos(b/e*(Math.PI/2))+d+c},easeOutSine:function(a,b,c,d,e){return d*Math.sin(b/e*(Math.PI/2))+c},easeInOutSine:function(a,b,c,d,e){return-d/2*(Math.cos(Math.PI*b/e)-1)+c},easeInExpo:function(a,b,c,d,e){return b==0?c:d*Math.pow(2,10*(b/e-1))+c},easeOutExpo:function(a,b,c,d,e){return b==e?c+d:d*(-Math.pow(2,-10*b/e)+1)+c},easeInOutExpo:function(a,b,c,d,e){return b==0?c:b==e?c+d:(b/=e/2)<1?d/2*Math.pow(2,10*(b-1))+c:d/2*(-Math.pow(2,-10*--b)+2)+c},easeInCirc:function(a,b,c,d,e){return-d*(Math.sqrt(1-(b/=e)*b)-1)+c},easeOutCirc:function(a,b,c,d,e){return d*Math.sqrt(1-(b=b/e-1)*b)+c},easeInOutCirc:function(a,b,c,d,e){return(b/=e/2)<1?-d/2*(Math.sqrt(1-b*b)-1)+c:d/2*(Math.sqrt(1-(b-=2)*b)+1)+c},easeInElastic:function(a,b,c,d,e){var f=1.70158,g=0,h=d;if(b==0)return c;if((b/=e)==1)return c+d;g||(g=e*.3);if(h<Math.abs(d)){h=d;var f=g/4}else var f=g/(2*Math.PI)*Math.asin(d/h);return-(h*Math.pow(2,10*(b-=1))*Math.sin((b*e-f)*2*Math.PI/g))+c},easeOutElastic:function(a,b,c,d,e){var f=1.70158,g=0,h=d;if(b==0)return c;if((b/=e)==1)return c+d;g||(g=e*.3);if(h<Math.abs(d)){h=d;var f=g/4}else var f=g/(2*Math.PI)*Math.asin(d/h);return h*Math.pow(2,-10*b)*Math.sin((b*e-f)*2*Math.PI/g)+d+c},easeInOutElastic:function(a,b,c,d,e){var f=1.70158,g=0,h=d;if(b==0)return c;if((b/=e/2)==2)return c+d;g||(g=e*.3*1.5);if(h<Math.abs(d)){h=d;var f=g/4}else var f=g/(2*Math.PI)*Math.asin(d/h);return b<1?-0.5*h*Math.pow(2,10*(b-=1))*Math.sin((b*e-f)*2*Math.PI/g)+c:h*Math.pow(2,-10*(b-=1))*Math.sin((b*e-f)*2*Math.PI/g)*.5+d+c},easeInBack:function(a,c,d,e,f,g){return g==b&&(g=1.70158),e*(c/=f)*c*((g+1)*c-g)+d},easeOutBack:function(a,c,d,e,f,g){return g==b&&(g=1.70158),e*((c=c/f-1)*c*((g+1)*c+g)+1)+d},easeInOutBack:function(a,c,d,e,f,g){return g==b&&(g=1.70158),(c/=f/2)<1?e/2*c*c*(((g*=1.525)+1)*c-g)+d:e/2*((c-=2)*c*(((g*=1.525)+1)*c+g)+2)+d},easeInBounce:function(b,c,d,e,f){return e-a.easing.easeOutBounce(b,f-c,0,e,f)+d},easeOutBounce:function(a,b,c,d,e){return(b/=e)<1/2.75?d*7.5625*b*b+c:b<2/2.75?d*(7.5625*(b-=1.5/2.75)*b+.75)+c:b<2.5/2.75?d*(7.5625*(b-=2.25/2.75)*b+.9375)+c:d*(7.5625*(b-=2.625/2.75)*b+.984375)+c},easeInOutBounce:function(b,c,d,e,f){return c<f/2?a.easing.easeInBounce(b,c*2,0,e,f)*.5+d:a.easing.easeOutBounce(b,c*2-f,0,e,f)*.5+e*.5+d}})}(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1573 * https://github.com/jquery/jquery-ui
1574 * Includes: jquery.effects.blind.js
1575 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1576 (function(a,b){a.effects.blind=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.direction||"vertical";a.effects.save(c,d),c.show();var g=a.effects.createWrapper(c).css({overflow:"hidden"}),h=f=="vertical"?"height":"width",i=f=="vertical"?g.height():g.width();e=="show"&&g.css(h,0);var j={};j[h]=e=="show"?i:0,g.animate(j,b.duration,b.options.easing,function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1577 * https://github.com/jquery/jquery-ui
1578 * Includes: jquery.effects.bounce.js
1579 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1580 (function(a,b){a.effects.bounce=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"effect"),f=b.options.direction||"up",g=b.options.distance||20,h=b.options.times||5,i=b.duration||250;/show|hide/.test(e)&&d.push("opacity"),a.effects.save(c,d),c.show(),a.effects.createWrapper(c);var j=f=="up"||f=="down"?"top":"left",k=f=="up"||f=="left"?"pos":"neg",g=b.options.distance||(j=="top"?c.outerHeight({margin:!0})/3:c.outerWidth({margin:!0})/3);e=="show"&&c.css("opacity",0).css(j,k=="pos"?-g:g),e=="hide"&&(g=g/(h*2)),e!="hide"&&h--;if(e=="show"){var l={opacity:1};l[j]=(k=="pos"?"+=":"-=")+g,c.animate(l,i/2,b.options.easing),g=g/2,h--}for(var m=0;m<h;m++){var n={},p={};n[j]=(k=="pos"?"-=":"+=")+g,p[j]=(k=="pos"?"+=":"-=")+g,c.animate(n,i/2,b.options.easing).animate(p,i/2,b.options.easing),g=e=="hide"?g*2:g/2}if(e=="hide"){var l={opacity:0};l[j]=(k=="pos"?"-=":"+=")+g,c.animate(l,i/2,b.options.easing,function(){c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments)})}else{var n={},p={};n[j]=(k=="pos"?"-=":"+=")+g,p[j]=(k=="pos"?"+=":"-=")+g,c.animate(n,i/2,b.options.easing).animate(p,i/2,b.options.easing,function(){a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments)})}c.queue("fx",function(){c.dequeue()}),c.dequeue()})}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1581 * https://github.com/jquery/jquery-ui
1582 * Includes: jquery.effects.clip.js
1583 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1584 (function(a,b){a.effects.clip=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right","height","width"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.direction||"vertical";a.effects.save(c,d),c.show();var g=a.effects.createWrapper(c).css({overflow:"hidden"}),h=c[0].tagName=="IMG"?g:c,i={size:f=="vertical"?"height":"width",position:f=="vertical"?"top":"left"},j=f=="vertical"?h.height():h.width();e=="show"&&(h.css(i.size,0),h.css(i.position,j/2));var k={};k[i.size]=e=="show"?j:0,k[i.position]=e=="show"?0:j/2,h.animate(k,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()}})})}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1585 * https://github.com/jquery/jquery-ui
1586 * Includes: jquery.effects.drop.js
1587 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1588 (function(a,b){a.effects.drop=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right","opacity"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.direction||"left";a.effects.save(c,d),c.show(),a.effects.createWrapper(c);var g=f=="up"||f=="down"?"top":"left",h=f=="up"||f=="left"?"pos":"neg",i=b.options.distance||(g=="top"?c.outerHeight({margin:!0})/2:c.outerWidth({margin:!0})/2);e=="show"&&c.css("opacity",0).css(g,h=="pos"?-i:i);var j={opacity:e=="show"?1:0};j[g]=(e=="show"?h=="pos"?"+=":"-=":h=="pos"?"-=":"+=")+i,c.animate(j,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1589 * https://github.com/jquery/jquery-ui
1590 * Includes: jquery.effects.explode.js
1591 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1592 (function(a,b){a.effects.explode=function(b){return this.queue(function(){var c=b.options.pieces?Math.round(Math.sqrt(b.options.pieces)):3,d=b.options.pieces?Math.round(Math.sqrt(b.options.pieces)):3;b.options.mode=b.options.mode=="toggle"?a(this).is(":visible")?"hide":"show":b.options.mode;var e=a(this).show().css("visibility","hidden"),f=e.offset();f.top-=parseInt(e.css("marginTop"),10)||0,f.left-=parseInt(e.css("marginLeft"),10)||0;var g=e.outerWidth(!0),h=e.outerHeight(!0);for(var i=0;i<c;i++)for(var j=0;j<d;j++)e.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-j*(g/d),top:-i*(h/c)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:g/d,height:h/c,left:f.left+j*(g/d)+(b.options.mode=="show"?(j-Math.floor(d/2))*(g/d):0),top:f.top+i*(h/c)+(b.options.mode=="show"?(i-Math.floor(c/2))*(h/c):0),opacity:b.options.mode=="show"?0:1}).animate({left:f.left+j*(g/d)+(b.options.mode=="show"?0:(j-Math.floor(d/2))*(g/d)),top:f.top+i*(h/c)+(b.options.mode=="show"?0:(i-Math.floor(c/2))*(h/c)),opacity:b.options.mode=="show"?1:0},b.duration||500);setTimeout(function(){b.options.mode=="show"?e.css({visibility:"visible"}):e.css({visibility:"visible"}).hide(),b.callback&&b.callback.apply(e[0]),e.dequeue(),a("div.ui-effects-explode").remove()},b.duration||500)})}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1593 * https://github.com/jquery/jquery-ui
1594 * Includes: jquery.effects.fade.js
1595 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1596 (function(a,b){a.effects.fade=function(b){return this.queue(function(){var c=a(this),d=a.effects.setMode(c,b.options.mode||"hide");c.animate({opacity:d},{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1597 * https://github.com/jquery/jquery-ui
1598 * Includes: jquery.effects.fold.js
1599 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1600 (function(a,b){a.effects.fold=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"hide"),f=b.options.size||15,g=!!b.options.horizFirst,h=b.duration?b.duration/2:a.fx.speeds._default/2;a.effects.save(c,d),c.show();var i=a.effects.createWrapper(c).css({overflow:"hidden"}),j=e=="show"!=g,k=j?["width","height"]:["height","width"],l=j?[i.width(),i.height()]:[i.height(),i.width()],m=/([0-9]+)%/.exec(f);m&&(f=parseInt(m[1],10)/100*l[e=="hide"?0:1]),e=="show"&&i.css(g?{height:0,width:f}:{height:f,width:0});var n={},p={};n[k[0]]=e=="show"?l[0]:f,p[k[1]]=e=="show"?l[1]:0,i.animate(n,h,b.options.easing).animate(p,h,b.options.easing,function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1601 * https://github.com/jquery/jquery-ui
1602 * Includes: jquery.effects.highlight.js
1603 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1604 (function(a,b){a.effects.highlight=function(b){return this.queue(function(){var c=a(this),d=["backgroundImage","backgroundColor","opacity"],e=a.effects.setMode(c,b.options.mode||"show"),f={backgroundColor:c.css("backgroundColor")};e=="hide"&&(f.opacity=0),a.effects.save(c,d),c.show().css({backgroundImage:"none",backgroundColor:b.options.color||"#ffff99"}).animate(f,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),e=="show"&&!a.support.opacity&&this.style.removeAttribute("filter"),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1605 * https://github.com/jquery/jquery-ui
1606 * Includes: jquery.effects.pulsate.js
1607 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1608 (function(a,b){a.effects.pulsate=function(b){return this.queue(function(){var c=a(this),d=a.effects.setMode(c,b.options.mode||"show"),e=(b.options.times||5)*2-1,f=b.duration?b.duration/2:a.fx.speeds._default/2,g=c.is(":visible"),h=0;g||(c.css("opacity",0).show(),h=1),(d=="hide"&&g||d=="show"&&!g)&&e--;for(var i=0;i<e;i++)c.animate({opacity:h},f,b.options.easing),h=(h+1)%2;c.animate({opacity:h},f,b.options.easing,function(){h==0&&c.hide(),b.callback&&b.callback.apply(this,arguments)}),c.queue("fx",function(){c.dequeue()}).dequeue()})}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1609 * https://github.com/jquery/jquery-ui
1610 * Includes: jquery.effects.scale.js
1611 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1612 (function(a,b){a.effects.puff=function(b){return this.queue(function(){var c=a(this),d=a.effects.setMode(c,b.options.mode||"hide"),e=parseInt(b.options.percent,10)||150,f=e/100,g={height:c.height(),width:c.width()};a.extend(b.options,{fade:!0,mode:d,percent:d=="hide"?e:100,from:d=="hide"?g:{height:g.height*f,width:g.width*f}}),c.effect("scale",b.options,b.duration,b.callback),c.dequeue()})},a.effects.scale=function(b){return this.queue(function(){var c=a(this),d=a.extend(!0,{},b.options),e=a.effects.setMode(c,b.options.mode||"effect"),f=parseInt(b.options.percent,10)||(parseInt(b.options.percent,10)==0?0:e=="hide"?0:100),g=b.options.direction||"both",h=b.options.origin;e!="effect"&&(d.origin=h||["middle","center"],d.restore=!0);var i={height:c.height(),width:c.width()};c.from=b.options.from||(e=="show"?{height:0,width:0}:i);var j={y:g!="horizontal"?f/100:1,x:g!="vertical"?f/100:1};c.to={height:i.height*j.y,width:i.width*j.x},b.options.fade&&(e=="show"&&(c.from.opacity=0,c.to.opacity=1),e=="hide"&&(c.from.opacity=1,c.to.opacity=0)),d.from=c.from,d.to=c.to,d.mode=e,c.effect("size",d,b.duration,b.callback),c.dequeue()})},a.effects.size=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right","width","height","overflow","opacity"],e=["position","top","bottom","left","right","overflow","opacity"],f=["width","height","overflow"],g=["fontSize"],h=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],i=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],j=a.effects.setMode(c,b.options.mode||"effect"),k=b.options.restore||!1,l=b.options.scale||"both",m=b.options.origin,n={height:c.height(),width:c.width()};c.from=b.options.from||n,c.to=b.options.to||n;if(m){var p=a.effects.getBaseline(m,n);c.from.top=(n.height-c.from.height)*p.y,c.from.left=(n.width-c.from.width)*p.x,c.to.top=(n.height-c.to.height)*p.y,c.to.left=(n.width-c.to.width)*p.x}var q={from:{y:c.from.height/n.height,x:c.from.width/n.width},to:{y:c.to.height/n.height,x:c.to.width/n.width}};if(l=="box"||l=="both")q.from.y!=q.to.y&&(d=d.concat(h),c.from=a.effects.setTransition(c,h,q.from.y,c.from),c.to=a.effects.setTransition(c,h,q.to.y,c.to)),q.from.x!=q.to.x&&(d=d.concat(i),c.from=a.effects.setTransition(c,i,q.from.x,c.from),c.to=a.effects.setTransition(c,i,q.to.x,c.to));(l=="content"||l=="both")&&q.from.y!=q.to.y&&(d=d.concat(g),c.from=a.effects.setTransition(c,g,q.from.y,c.from),c.to=a.effects.setTransition(c,g,q.to.y,c.to)),a.effects.save(c,k?d:e),c.show(),a.effects.createWrapper(c),c.css("overflow","hidden").css(c.from);if(l=="content"||l=="both")h=h.concat(["marginTop","marginBottom"]).concat(g),i=i.concat(["marginLeft","marginRight"]),f=d.concat(h).concat(i),c.find("*[width]").each(function(){var c=a(this);k&&a.effects.save(c,f);var d={height:c.height(),width:c.width()};c.from={height:d.height*q.from.y,width:d.width*q.from.x},c.to={height:d.height*q.to.y,width:d.width*q.to.x},q.from.y!=q.to.y&&(c.from=a.effects.setTransition(c,h,q.from.y,c.from),c.to=a.effects.setTransition(c,h,q.to.y,c.to)),q.from.x!=q.to.x&&(c.from=a.effects.setTransition(c,i,q.from.x,c.from),c.to=a.effects.setTransition(c,i,q.to.x,c.to)),c.css(c.from),c.animate(c.to,b.duration,b.options.easing,function(){k&&a.effects.restore(c,f)})});c.animate(c.to,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){c.to.opacity===0&&c.css("opacity",c.from.opacity),j=="hide"&&c.hide(),a.effects.restore(c,k?d:e),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1613 * https://github.com/jquery/jquery-ui
1614 * Includes: jquery.effects.shake.js
1615 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1616 (function(a,b){a.effects.shake=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"effect"),f=b.options.direction||"left",g=b.options.distance||20,h=b.options.times||3,i=b.duration||b.options.duration||140;a.effects.save(c,d),c.show(),a.effects.createWrapper(c);var j=f=="up"||f=="down"?"top":"left",k=f=="up"||f=="left"?"pos":"neg",l={},m={},n={};l[j]=(k=="pos"?"-=":"+=")+g,m[j]=(k=="pos"?"+=":"-=")+g*2,n[j]=(k=="pos"?"-=":"+=")+g*2,c.animate(l,i,b.options.easing);for(var p=1;p<h;p++)c.animate(m,i,b.options.easing).animate(n,i,b.options.easing);c.animate(m,i,b.options.easing).animate(l,i/2,b.options.easing,function(){a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments)}),c.queue("fx",function(){c.dequeue()}),c.dequeue()})}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1617 * https://github.com/jquery/jquery-ui
1618 * Includes: jquery.effects.slide.js
1619 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1620 (function(a,b){a.effects.slide=function(b){return this.queue(function(){var c=a(this),d=["position","top","bottom","left","right"],e=a.effects.setMode(c,b.options.mode||"show"),f=b.options.direction||"left";a.effects.save(c,d),c.show(),a.effects.createWrapper(c).css({overflow:"hidden"});var g=f=="up"||f=="down"?"top":"left",h=f=="up"||f=="left"?"pos":"neg",i=b.options.distance||(g=="top"?c.outerHeight({margin:!0}):c.outerWidth({margin:!0}));e=="show"&&c.css(g,h=="pos"?isNaN(i)?"-"+i:-i:i);var j={};j[g]=(e=="show"?h=="pos"?"+=":"-=":h=="pos"?"-=":"+=")+i,c.animate(j,{queue:!1,duration:b.duration,easing:b.options.easing,complete:function(){e=="hide"&&c.hide(),a.effects.restore(c,d),a.effects.removeWrapper(c),b.callback&&b.callback.apply(this,arguments),c.dequeue()}})})}})(jQuery);;/*! jQuery UI - v1.8.21 - 2012-06-05
1621 * https://github.com/jquery/jquery-ui
1622 * Includes: jquery.effects.transfer.js
1623 * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */
1624 (function(a,b){a.effects.transfer=function(b){return this.queue(function(){var c=a(this),d=a(b.options.to),e=d.offset(),f={top:e.top,left:e.left,height:d.innerHeight(),width:d.innerWidth()},g=c.offset(),h=a('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(b.options.className).css({top:g.top,left:g.left,height:c.innerHeight(),width:c.innerWidth(),position:"absolute"}).animate(f,b.duration,b.options.easing,function(){h.remove(),b.callback&&b.callback.apply(c[0],arguments),c.dequeue()})})}})(jQuery);;
1625 /*
1626 json2.js
1627 2011-10-19
1628 
1629 Public Domain.
1630 
1631 NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
1632 
1633 See http://www.JSON.org/js.html
1634 
1635 
1636 This code should be minified before deployment.
1637 See http://javascript.crockford.com/jsmin.html
1638 
1639 USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
1640 NOT CONTROL.
1641 
1642 
1643 This file creates a global JSON object containing two methods: stringify
1644 and parse.
1645 
1646 JSON.stringify(value, replacer, space)
1647 value any JavaScript value, usually an object or array.
1648 
1649 replacer an optional parameter that determines how object
1650 values are stringified for objects. It can be a
1651 function or an array of strings.
1652 
1653 space an optional parameter that specifies the indentation
1654 of nested structures. If it is omitted, the text will
1655 be packed without extra whitespace. If it is a number,
1656 it will specify the number of spaces to indent at each
1657 level. If it is a string (such as '\t' or ' '),
1658 it contains the characters used to indent at each level.
1659 
1660 This method produces a JSON text from a JavaScript value.
1661 
1662 When an object value is found, if the object contains a toJSON
1663 method, its toJSON method will be called and the result will be
1664 stringified. A toJSON method does not serialize: it returns the
1665 value represented by the name/value pair that should be serialized,
1666 or undefined if nothing should be serialized. The toJSON method
1667 will be passed the key associated with the value, and this will be
1668 bound to the value
1669 
1670 For example, this would serialize Dates as ISO strings.
1671 
1672 Date.prototype.toJSON = function (key) {
1673 function f(n) {
1674 // Format integers to have at least two digits.
1675 return n < 10 ? '0' + n : n;
1676 }
1677 
1678 return this.getUTCFullYear() + '-' +
1679 f(this.getUTCMonth() + 1) + '-' +
1680 f(this.getUTCDate()) + 'T' +
1681 f(this.getUTCHours()) + ':' +
1682 f(this.getUTCMinutes()) + ':' +
1683 f(this.getUTCSeconds()) + 'Z';
1684 };
1685 
1686 You can provide an optional replacer method. It will be passed the
1687 key and value of each member, with this bound to the containing
1688 object. The value that is returned from your method will be
1689 serialized. If your method returns undefined, then the member will
1690 be excluded from the serialization.
1691 
1692 If the replacer parameter is an array of strings, then it will be
1693 used to select the members to be serialized. It filters the results
1694 such that only members with keys listed in the replacer array are
1695 stringified.
1696 
1697 Values that do not have JSON representations, such as undefined or
1698 functions, will not be serialized. Such values in objects will be
1699 dropped; in arrays they will be replaced with null. You can use
1700 a replacer function to replace those with JSON values.
1701 JSON.stringify(undefined) returns undefined.
1702 
1703 The optional space parameter produces a stringification of the
1704 value that is filled with line breaks and indentation to make it
1705 easier to read.
1706 
1707 If the space parameter is a non-empty string, then that string will
1708 be used for indentation. If the space parameter is a number, then
1709 the indentation will be that many spaces.
1710 
1711 Example:
1712 
1713 text = JSON.stringify(['e', {pluribus: 'unum'}]);
1714 // text is '["e",{"pluribus":"unum"}]'
1715 
1716 
1717 text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
1718 // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
1719 
1720 text = JSON.stringify([new Date()], function (key, value) {
1721 return this[key] instanceof Date ?
1722 'Date(' + this[key] + ')' : value;
1723 });
1724 // text is '["Date(---current time---)"]'
1725 
1726 
1727 JSON.parse(text, reviver)
1728 This method parses a JSON text to produce an object or array.
1729 It can throw a SyntaxError exception.
1730 
1731 The optional reviver parameter is a function that can filter and
1732 transform the results. It receives each of the keys and values,
1733 and its return value is used instead of the original value.
1734 If it returns what it received, then the structure is not modified.
1735 If it returns undefined then the member is deleted.
1736 
1737 Example:
1738 
1739 // Parse the text. Values that look like ISO date strings will
1740 // be converted to Date objects.
1741 
1742 myData = JSON.parse(text, function (key, value) {
1743 var a;
1744 if (typeof value === 'string') {
1745 a =
1746 /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
1747 if (a) {
1748 return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
1749 +a[5], +a[6]));
1750 }
1751 }
1752 return value;
1753 });
1754 
1755 myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
1756 var d;
1757 if (typeof value === 'string' &&
1758 value.slice(0, 5) === 'Date(' &&
1759 value.slice(-1) === ')') {
1760 d = new Date(value.slice(5, -1));
1761 if (d) {
1762 return d;
1763 }
1764 }
1765 return value;
1766 });
1767 
1768 
1769 This is a reference implementation. You are free to copy, modify, or
1770 redistribute.
1771 */
1772 
1773 /*jslint evil: true, regexp: true */
1774 
1775 /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
1776 call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
1777 getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
1778 lastIndex, length, parse, prototype, push, replace, slice, stringify,
1779 test, toJSON, toString, valueOf
1780 */
1781 
1782 
1783 // Create a JSON object only if one does not already exist. We create the
1784 // methods in a closure to avoid creating global variables.
1785 
1786 var JSON;
1787 if (!JSON) {
1788     JSON = {};
1789 }
1790 
1791 (function () {
1792     'use strict';
1793 
1794     function f(n) {
1795         // Format integers to have at least two digits.
1796         return n < 10 ? '0' + n : n;
1797     }
1798 
1799     if (typeof Date.prototype.toJSON !== 'function') {
1800 
1801         Date.prototype.toJSON = function (key) {
1802 
1803             return isFinite(this.valueOf())
1804                 ? this.getUTCFullYear() + '-' +
1805                     f(this.getUTCMonth() + 1) + '-' +
1806                     f(this.getUTCDate()) + 'T' +
1807                     f(this.getUTCHours()) + ':' +
1808                     f(this.getUTCMinutes()) + ':' +
1809                     f(this.getUTCSeconds()) + 'Z'
1810                 : null;
1811         };
1812 
1813         String.prototype.toJSON =
1814             Number.prototype.toJSON =
1815             Boolean.prototype.toJSON = function (key) {
1816                 return this.valueOf();
1817             };
1818     }
1819 
1820     var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
1821         escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
1822         gap,
1823         indent,
1824         meta = { // table of character substitutions
1825             '\b': '\\b',
1826             '\t': '\\t',
1827             '\n': '\\n',
1828             '\f': '\\f',
1829             '\r': '\\r',
1830             '"' : '\\"',
1831             '\\': '\\\\'
1832         },
1833         rep;
1834 
1835 
1836     function quote(string) {
1837 
1838 // If the string contains no control characters, no quote characters, and no
1839 // backslash characters, then we can safely slap some quotes around it.
1840 // Otherwise we must also replace the offending characters with safe escape
1841 // sequences.
1842 
1843         escapable.lastIndex = 0;
1844         return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
1845             var c = meta[a];
1846             return typeof c === 'string'
1847                 ? c
1848                 : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
1849         }) + '"' : '"' + string + '"';
1850     }
1851 
1852 
1853     function str(key, holder) {
1854 
1855 // Produce a string from holder[key].
1856 
1857         var i, // The loop counter.
1858             k, // The member key.
1859             v, // The member value.
1860             length,
1861             mind = gap,
1862             partial,
1863             value = holder[key];
1864 
1865 // If the value has a toJSON method, call it to obtain a replacement value.
1866 
1867         if (value && typeof value === 'object' &&
1868                 typeof value.toJSON === 'function') {
1869             value = value.toJSON(key);
1870         }
1871 
1872 // If we were called with a replacer function, then call the replacer to
1873 // obtain a replacement value.
1874 
1875         if (typeof rep === 'function') {
1876             value = rep.call(holder, key, value);
1877         }
1878 
1879 // What happens next depends on the value's type.
1880 
1881         switch (typeof value) {
1882         case 'string':
1883             return quote(value);
1884 
1885         case 'number':
1886 
1887 // JSON numbers must be finite. Encode non-finite numbers as null.
1888 
1889             return isFinite(value) ? String(value) : 'null';
1890 
1891         case 'boolean':
1892         case 'null':
1893 
1894 // If the value is a boolean or null, convert it to a string. Note:
1895 // typeof null does not produce 'null'. The case is included here in
1896 // the remote chance that this gets fixed someday.
1897 
1898             return String(value);
1899 
1900 // If the type is 'object', we might be dealing with an object or an array or
1901 // null.
1902 
1903         case 'object':
1904 
1905 // Due to a specification blunder in ECMAScript, typeof null is 'object',
1906 // so watch out for that case.
1907 
1908             if (!value) {
1909                 return 'null';
1910             }
1911 
1912 // Make an array to hold the partial results of stringifying this object value.
1913 
1914             gap += indent;
1915             partial = [];
1916 
1917 // Is the value an array?
1918 
1919             if (Object.prototype.toString.apply(value) === '[object Array]') {
1920 
1921 // The value is an array. Stringify every element. Use null as a placeholder
1922 // for non-JSON values.
1923 
1924                 length = value.length;
1925                 for (i = 0; i < length; i += 1) {
1926                     partial[i] = str(i, value) || 'null';
1927                 }
1928 
1929 // Join all of the elements together, separated with commas, and wrap them in
1930 // brackets.
1931 
1932                 v = partial.length === 0
1933                     ? '[]'
1934                     : gap
1935                     ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
1936                     : '[' + partial.join(',') + ']';
1937                 gap = mind;
1938                 return v;
1939             }
1940 
1941 // If the replacer is an array, use it to select the members to be stringified.
1942 
1943             if (rep && typeof rep === 'object') {
1944                 length = rep.length;
1945                 for (i = 0; i < length; i += 1) {
1946                     if (typeof rep[i] === 'string') {
1947                         k = rep[i];
1948                         v = str(k, value);
1949                         if (v) {
1950                             partial.push(quote(k) + (gap ? ': ' : ':') + v);
1951                         }
1952                     }
1953                 }
1954             } else {
1955 
1956 // Otherwise, iterate through all of the keys in the object.
1957 
1958                 for (k in value) {
1959                     if (Object.prototype.hasOwnProperty.call(value, k)) {
1960                         v = str(k, value);
1961                         if (v) {
1962                             partial.push(quote(k) + (gap ? ': ' : ':') + v);
1963                         }
1964                     }
1965                 }
1966             }
1967 
1968 // Join all of the member texts together, separated with commas,
1969 // and wrap them in braces.
1970 
1971             v = partial.length === 0
1972                 ? '{}'
1973                 : gap
1974                 ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
1975                 : '{' + partial.join(',') + '}';
1976             gap = mind;
1977             return v;
1978         }
1979     }
1980 
1981 // If the JSON object does not yet have a stringify method, give it one.
1982 
1983     if (typeof JSON.stringify !== 'function') {
1984         JSON.stringify = function (value, replacer, space) {
1985            
1986 // The stringify method takes a value and an optional replacer, and an optional
1987 // space parameter, and returns a JSON text. The replacer can be a function
1988 // that can replace values, or an array of strings that will select the keys.
1989 // A default replacer method can be provided. Use of the space parameter can
1990 // produce text that is more easily readable.
1991 
1992             var i;
1993             gap = '';
1994             indent = '';
1995 
1996 // If the space parameter is a number, make an indent string containing that
1997 // many spaces.
1998 
1999             if (typeof space === 'number') {
2000                 for (i = 0; i < space; i += 1) {
2001                     indent += ' ';
2002                 }
2003 
2004 // If the space parameter is a string, it will be used as the indent string.
2005 
2006             } else if (typeof space === 'string') {
2007                 indent = space;
2008             }
2009 
2010 // If there is a replacer, it must be a function or an array.
2011 // Otherwise, throw an error.
2012 
2013             rep = replacer;
2014             if (replacer && typeof replacer !== 'function' &&
2015                     (typeof replacer !== 'object' ||
2016                     typeof replacer.length !== 'number')) {
2017                 throw new Error('JSON.stringify');
2018             }
2019 
2020 // Make a fake root object containing our value under the key of ''.
2021 // Return the result of stringifying the value.
2022 
2023             return str('', {'': value});
2024         };
2025         JSON.toString = JSON.stringify;
2026         window['JSON']['stringify'] = JSON.stringify; 
2027         window['JSON']['toString'] = JSON.stringify; 
2028     }
2029 
2030 
2031 // If the JSON object does not yet have a parse method, give it one.
2032 
2033     if (typeof JSON.parse !== 'function') {
2034         JSON.parse = function (text, reviver) {
2035 
2036 // The parse method takes a text and an optional reviver function, and returns
2037 // a JavaScript value if the text is a valid JSON text.
2038 
2039             var j;
2040 
2041             function walk(holder, key) {
2042 
2043 // The walk method is used to recursively walk the resulting structure so
2044 // that modifications can be made.
2045 
2046                 var k, v, value = holder[key];
2047                 if (value && typeof value === 'object') {
2048                     for (k in value) {
2049                         if (Object.prototype.hasOwnProperty.call(value, k)) {
2050                             v = walk(value, k);
2051                             if (v !== undefined) {
2052                                 value[k] = v;
2053                             } else {
2054                                 delete value[k];
2055                             }
2056                         }
2057                     }
2058                 }
2059                 return reviver.call(holder, key, value);
2060             }
2061 
2062 
2063 // Parsing happens in four stages. In the first stage, we replace certain
2064 // Unicode characters with escape sequences. JavaScript handles many characters
2065 // incorrectly, either silently deleting them, or treating them as line endings.
2066 
2067             text = String(text);
2068             cx.lastIndex = 0;
2069             if (cx.test(text)) {
2070                 text = text.replace(cx, function (a) {
2071                     return '\\u' +
2072                         ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
2073                 });
2074             }
2075 
2076 // In the second stage, we run the text against regular expressions that look
2077 // for non-JSON patterns. We are especially concerned with '()' and 'new'
2078 // because they can cause invocation, and '=' because it can cause mutation.
2079 // But just to be safe, we want to reject all unexpected forms.
2080 
2081 // We split the second stage into 4 regexp operations in order to work around
2082 // crippling inefficiencies in IE's and Safari's regexp engines. First we
2083 // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
2084 // replace all simple value tokens with ']' characters. Third, we delete all
2085 // open brackets that follow a colon or comma or that begin the text. Finally,
2086 // we look to see that the remaining characters are only whitespace or ']' or
2087 // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
2088 
2089             if (/^[\],:{}\s]*$/
2090                     .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
2091                         .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
2092                         .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
2093 
2094 // In the third stage we use the eval function to compile the text into a
2095 // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
2096 // in JavaScript: it can begin a block or an object literal. We wrap the text
2097 // in parens to eliminate the ambiguity.
2098 
2099                 j = eval('(' + text + ')');
2100 
2101 // In the optional fourth stage, we recursively walk the new structure, passing
2102 // each name/value pair to a reviver function for possible transformation.
2103 
2104                 return typeof reviver === 'function'
2105                     ? walk({'': j}, '')
2106                     : j;
2107             }
2108 
2109 // If the text is not JSON parseable, then a SyntaxError is thrown.
2110 
2111             throw new SyntaxError('JSON.parse');
2112         };
2113         JSON.create = JSON.parse;
2114         window['JSON']['create'] = JSON.parse;
2115         window['JSON']['parse'] = JSON.parse;
2116     }
2117 }());
2118 /*
2119  * Copyright (c) 2006-2011, The Flapjax Team.  All Rights Reserved.
2120  *  
2121  * Redistribution and use in source and binary forms, with or without
2122  * modification, are permitted provided that the following conditions are
2123  * met:
2124  * 
2125  * * Redistributions of source code must retain the above copyright notice,
2126  *   this list of conditions and the following disclaimer.
2127  * * Redistributions in binary form must reproduce the above copyright notice,
2128  *   this list of conditions and the following disclaimer in the documentation
2129  *   and/or other materials provided with the distribution.
2130  * * Neither the name of the Brown University, the Flapjax Team, nor the names
2131  *   of its contributors may be used to endorse or promote products derived
2132  *   from this software without specific prior written permission.
2133  * 
2134  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2135  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2136  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2137  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2138  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2139  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2140  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2141  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2142  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2143  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2144  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2145  * 
2146  */
2147   
2148 ///////////////////////////////////////////////////////////////////////////////
2149 // Miscellaneous functions
2150 
2151 
2152 
2153 
2154 if (!Array.prototype.map) {
2155   Array.prototype.map = function(callback, thisArg) {
2156     var T, A, k;
2157     if (this == null) {
2158       throw new TypeError(" this is null or not defined");
2159     }
2160     var O = Object(this);
2161     var len = O.length >>> 0;
2162     if ({}.toString.call(callback) != "[object Function]") {
2163       throw new TypeError(callback + " is not a function");
2164     }
2165     if (thisArg) {
2166       T = thisArg;
2167     }
2168     A = new Array(len); 
2169     k = 0;
2170     while(k < len) {
2171       var kValue, mappedValue;
2172       if (k in O) {
2173         kValue = O[ k ];
2174         mappedValue = callback.call(T, kValue, k, O);
2175         A[ k ] = mappedValue;
2176       }
2177       k++;
2178     }
2179     return A;
2180   };      
2181 }
2182 
2183 
2184 
2185 
2186 
2187 
2188 // Hacks to build standalone or as a module.           
2189 /** @suppress JSC_UNDEFINED_VARIABLE */
2190 var gProvide = goog['provide'];
2191 gProvide('F');
2192 
2193 //goog.provide('flapjax');
2194 
2195 /**
2196  * @namespace Flapjax
2197  */
2198 F = F || { };
2199 flapjax = F;
2200 
2201 
2202 /**
2203  * @namespace
2204  */
2205 F.internal_ = { };
2206 /**
2207  * @namespace
2208  */
2209 F.dom_ = { };
2210 /**
2211  * @namespace
2212  */
2213 F.xhr_ = { };
2214 
2215 // Sentinel value returned by updaters to stop propagation.
2216 F.doNotPropagate = { };
2217 
2218 /**
2219  * @returns {Array}
2220  */
2221 F.mkArray = function(arrayLike) {
2222   return Array.prototype.slice.call(arrayLike);
2223 };
2224 
2225 
2226 
2227 
2228 
2229 
2230 
2231 
2232    
2233                var module = this;
2234 
2235 //credit 4umi
2236 //slice: Array a * Integer * Integer -> Array a
2237 F.slice = function (arr, start, stop) {
2238   var i, len = arr.length, r = [];
2239   if( !stop ) { stop = len; }
2240   if( stop < 0 ) { stop = len + stop; }
2241   if( start < 0 ) { start = len - start; }
2242   if( stop < start ) { i = start; start = stop; stop = i; }
2243   for( i = 0; i < stop - start; i++ ) { r[i] = arr[start+i]; }
2244   return r;
2245 }
2246 
2247 F.isEqual = function (a,b) {
2248   return (a == b) ||
2249     ( (((typeof(a) == 'number') && isNaN(a)) || a == 'NaN') &&
2250       (((typeof(b) == 'number') && isNaN(b)) || b == 'NaN') );
2251 };
2252 
2253 F.forEach = function(fn,arr) {
2254   for (var i = 0 ; i < arr.length; i++) {
2255     fn(arr[i]);
2256   }
2257 };
2258 
2259 //member: a * Array b -> Boolean
2260 F.member = function(elt, lst) {
2261   for (var i = 0; i < lst.length; i++) { 
2262     if (isEqual(lst[i], elt)) {return true;} 
2263   }
2264   return false;
2265 };
2266 
2267 F.zip = function(arrays) {
2268   if (arrays.length == 0) return [];
2269   var ret = [];
2270   for(var i=0; i<arrays[0].length;i++) {
2271     ret.push([]);
2272     for(var j=0; j<arrays.length;j++) 
2273       ret[i].push(arrays[j][i]);
2274   }
2275   return ret;
2276 }
2277 
2278 //map: (a * ... -> z) * [a] * ... -> [z]
2279 F.map = function (fn) {
2280   var arrays = F.slice(arguments, 1);
2281   if (arrays.length === 0) { return []; }
2282   else if (arrays.length === 1) {
2283     var ret = [];
2284     for(var i=0; i<arrays[0].length; i++) {ret.push(fn(arrays[0][i]));}
2285     return ret;
2286   }
2287   else {
2288     var ret = F.zip(arrays);
2289     var o = new Object();
2290     for(var i=0; i<ret.length; i++) {ret[i] = fn.apply(o,ret[i]);}
2291     return ret;
2292   }
2293 };
2294 
2295 //filter: (a -> Boolean) * Array a -> Array a
2296 F.filter = function (predFn, arr) {
2297   var res = [];
2298   for (var i = 0; i < arr.length; i++) { 
2299     if (predFn(arr[i])) { res.push(arr[i]); }
2300   }
2301   return res;
2302 };
2303 
2304   
2305 //fold: (a * .... * accum -> accum) * accum * [a] * ... -> accum
2306 //fold over list(s), left to right
2307 F.fold = function(fn, init /* arrays */) {
2308   var lists = F.slice(arguments, 2);
2309   if (lists.length === 0) { return init; }
2310   else if(lists.length === 1) {
2311     var acc = init;
2312     for(var i = 0; i < lists[0].length; i++) {
2313       acc = fn(lists[0][i],acc);
2314     }
2315     return acc;
2316   }
2317   else {
2318     var acc = init;
2319     for (var i = 0; i < lists[0].length; i++) {
2320       var args = map( function (lst) { return lst[i];}, 
2321             lists);
2322       args.push(acc);
2323       acc = fn.apply({}, args);
2324     }
2325     return acc;
2326   }
2327 };
2328   
2329 //foldR: (a * .... * accum -> accum) * accum * [a] * ... -> accum
2330 //fold over list(s), right to left, fold more memory efficient (left to right)
2331 F.foldR = function (fn, init /* arrays */) {
2332   var lists = F.slice(arguments, 2);
2333   if (lists.length === 0) { return init; }
2334   else if(lists.length === 1) {
2335     var acc = init;
2336     for(var i=lists[0].length - 1; i > -1; i--)
2337       acc = fn(lists[0][i],acc);
2338     return acc;
2339   }
2340   else {
2341     var acc = init;
2342     for (var i = lists[0].length - 1; i > -1; i--) {
2343       var args = map( function (lst) { return lst[i];}, 
2344             lists);
2345       args.push(acc);
2346       acc = fn.apply({}, args);
2347     }
2348     return acc;     
2349   }
2350 };
2351 
2352 
2353 
2354 
2355 
2356 
2357 
2358 
2359 
2360 
2361 //////////////////////////////////////////////////////////////////////////////
2362 // Flapjax core
2363 
2364 /**
2365  * Stamp * Path * Obj
2366  * @constructor Pulse
2367  * @private
2368  */
2369 F.internal_.Pulse = function (stamp, value) {
2370   // Timestamps are used by F.liftB (and ifE).  Since F.liftB may receive multiple
2371   // update signals in the same run of the evaluator, it only propagates the 
2372   // signal if it has a new stamp.
2373   this.stamp = stamp;
2374   this.value = value;
2375 };
2376 
2377 /**
2378  * @constructor PQ
2379  * @private
2380  */
2381 F.internal_.PQ = function () {
2382   var ctx = this;
2383   ctx.val = [];
2384   this.insert = function (kv) {
2385     ctx.val.push(kv);
2386     var kvpos = ctx.val.length-1;
2387     while(kvpos > 0 && kv.k < ctx.val[Math.floor((kvpos-1)/2)].k) {
2388       var oldpos = kvpos;
2389       kvpos = Math.floor((kvpos-1)/2);
2390       ctx.val[oldpos] = ctx.val[kvpos];
2391       ctx.val[kvpos] = kv;
2392     }
2393   };
2394   this.isEmpty = function () { 
2395     return ctx.val.length === 0; 
2396   };
2397   this.pop = function () {
2398     if(ctx.val.length === 1) {
2399       return ctx.val.pop();
2400     }
2401     var ret = ctx.val.shift();
2402     ctx.val.unshift(ctx.val.pop());
2403     var kvpos = 0;
2404     var kv = ctx.val[0];
2405     while(1) { 
2406       var leftChild = (kvpos*2+1 < ctx.val.length ? ctx.val[kvpos*2+1].k : kv.k+1);
2407       var rightChild = (kvpos*2+2 < ctx.val.length ? ctx.val[kvpos*2+2].k : kv.k+1);
2408       if(leftChild > kv.k && rightChild > kv.k)
2409           break;
2410 
2411       if(leftChild < rightChild) {
2412         ctx.val[kvpos] = ctx.val[kvpos*2+1];
2413         ctx.val[kvpos*2+1] = kv;
2414         kvpos = kvpos*2+1;
2415       }
2416       else {
2417         ctx.val[kvpos] = ctx.val[kvpos*2+2];
2418         ctx.val[kvpos*2+2] = kv;
2419         kvpos = kvpos*2+2;
2420       }
2421     }
2422     return ret;
2423   };
2424 };
2425 
2426 F.internal_.lastRank = 0;
2427 F.internal_.stamp = 1;
2428 F.internal_.nextStamp = function () { return ++F.internal_.stamp; };
2429 
2430 //propagatePulse: Pulse * Array Node -> 
2431 //Send the pulse to each node 
2432 F.internal_.propagatePulse = function (pulse, node) {
2433   var queue = new F.internal_.PQ(); //topological queue for current timestep
2434 
2435   queue.insert({k:node.rank,n:node,v:pulse});
2436 
2437   while (!queue.isEmpty()) {
2438     var qv = queue.pop();
2439     var nextPulse = qv.n.updater(new F.internal_.Pulse(qv.v.stamp, qv.v.value));
2440 
2441     if (nextPulse != F.doNotPropagate) {
2442       for (var i = 0; i < qv.n.sendsTo.length; i++) {
2443   queue.insert({k:qv.n.sendsTo[i].rank,n:qv.n.sendsTo[i],v:nextPulse});
2444       }
2445     }
2446   }
2447 };
2448 
2449 /**
2450  * Event: Array Node b * ( (Pulse a -> Void) * Pulse b -> Void)
2451  * @constructor
2452  * @param {Array.<F.EventStream>} nodes
2453  */
2454 F.EventStream = function (nodes,updater) {
2455   this.updater = updater;
2456   
2457   this.sendsTo = []; //forward link
2458   
2459   this.rank = ++F.internal_.lastRank;
2460 
2461   for (var i = 0; i < nodes.length; i++) {
2462     nodes[i].attachListener(this);
2463   }
2464   
2465 };
2466 
2467 /**
2468  * note: does not add flow as counting for rank nor updates parent ranks
2469  * @param {F.EventStream} dependent
2470  */
2471 F.EventStream.prototype.attachListener = function(dependent) {
2472   if (!(dependent instanceof F.EventStream)) {
2473     throw 'attachListener: expected an F.EventStream';
2474   }
2475   this.sendsTo.push(dependent);
2476   
2477   if(this.rank > dependent.rank) {
2478     var q = [dependent];
2479     while(q.length) {
2480       var cur = q.splice(0,1)[0];
2481       cur.rank = ++F.internal_.lastRank;
2482       q = q.concat(cur.sendsTo);
2483     }
2484   }
2485 };
2486 
2487 //note: does not remove flow as counting for rank nor updates parent ranks
2488 F.EventStream.prototype.removeListener = function (dependent) {
2489   if (!(dependent instanceof F.EventStream)) {
2490     throw 'removeListener: expected an F.EventStream';
2491   }
2492 
2493   var foundSending = false;
2494   for (var i = 0; i < this.sendsTo.length && !foundSending; i++) {
2495     if (this.sendsTo[i] === dependent) {
2496       this.sendsTo.splice(i, 1);
2497       foundSending = true;
2498     }
2499   }
2500   
2501   return foundSending;
2502 };
2503 
2504 /**
2505  *An internalE is a node that propagates all pulses it receives.  It's used
2506  * internally by various combinators.
2507  *
2508  * @param {Array.<F.EventStream>=} dependsOn
2509  */
2510 F.internal_.internalE = function(dependsOn) {
2511   return new F.EventStream(dependsOn || [ ],function(pulse) { return pulse; });
2512 };
2513 
2514 /**
2515  * Create an event stream that never fires any events.
2516  * 
2517  * @returns {F.EventStream}
2518  */
2519 F.zeroE = function() {
2520   return new F.EventStream([],function(pulse) {
2521       throw ('zeroE : received a value; zeroE should not receive a value; the value was ' + pulse.value);
2522   });
2523 };
2524 
2525 
2526 /** 
2527  * Create an event stream that fires just one event with the value val.
2528  *
2529  * <p>Note that oneE does not immediately fire val. The event is queued and
2530  * fired after the current event has finished propagating.</p>
2531  *
2532  * <p>The following code prints "first", "second" and "third" in order:</p>
2533  *
2534  * @example
2535  * console.log('first');
2536  * F.oneE('third').mapE(function(val) { console.log(val); });
2537  * console.log('second');
2538  *
2539  * @param {*} val 
2540  * @returns {F.EventStream}
2541  */
2542 F.oneE = function(val) { 
2543   var sent = false; 
2544   var evt = new F.EventStream([],function(pulse) {
2545     if (sent) { throw ('oneE : received an extra value'); } sent = true; 
2546                 return pulse; }); 
2547   window.setTimeout(function() {
2548     F.sendEvent(evt,val); },0); 
2549   return evt;
2550 };
2551 
2552 
2553 /**
2554  * Triggers when any of the argument event stream trigger; carries the signal
2555  * from the last event stream that triggered.
2556  *
2557  * @param {...F.EventStream} var_args
2558  * @returns {F.EventStream}
2559  */
2560 F.mergeE = function(var_args) {
2561   if (arguments.length === 0) {
2562     return F.zeroE();
2563   }
2564   else {
2565     var deps = F.mkArray(arguments);
2566     return F.internal_.internalE(deps);
2567   }
2568 };
2569 
2570 F.EventStream.prototype.mergeE = function() {
2571   var deps = F.mkArray(arguments);
2572   deps.push(this);
2573   return F.internal_.internalE(deps);
2574 };
2575 
2576 /**
2577  * Transforms this event stream to produce only <code>constantValue</code>.
2578  *
2579  * @param {*} constantValue
2580  * @returns {F.EventStream}
2581  */
2582 F.EventStream.prototype.constantE = function(constantValue) {
2583   return new F.EventStream([this],function(pulse) {
2584     pulse.value = constantValue;
2585     return pulse;
2586   });
2587 };
2588                                   //(mid,getRes(),getRes, functionUp, parents)
2589 /**
2590  * @constructor
2591  * @param {F.EventStream} event
2592  * @param {*} init
2593  * @param {Function=} updater
2594  */
2595 F.Behavior = function (event, init, updater, upstreamTransformation, parents) {  
2596   if (!(event instanceof F.EventStream)) { 
2597     throw 'F.Behavior: expected event as second arg'; 
2598   }
2599   
2600   var behave = this;
2601   this.last = init;
2602   this.stamp = 0;
2603   
2604   //sendEvent to this might impact other nodes that depend on this event
2605   //sendF.Behavior defaults to this one
2606   this.underlyingRaw = event;
2607   
2608   //unexposed, sendEvent to this will only impact dependents of this behaviour
2609   this.underlying = new F.EventStream([event], updater 
2610     ? function (p) {
2611         behave.last = updater(p.value); 
2612         behave.stamp = p.stamp;
2613         p.value = behave.last; return p;
2614       } 
2615     : function (p) {
2616     	behave.stamp = p.stamp;
2617         behave.last = p.value;
2618         return p;
2619       });
2620     var upstreamEvent = F.receiverE(); 
2621     upstreamEvent.mapE(function(value){
2622     behave.last = value;
2623     if(upstreamTransformation!=undefined){
2624         var upstreamValues = upstreamTransformation(value);
2625         if(upstreamValues!=undefined){
2626             //log("upstreamValues Length: "+upstreamValues.length);
2627             //log(upstreamValues);
2628             if(upstreamValues.length==parents.length){
2629                 //log("Matching Return count");
2630                 for(index in parents){
2631                     //log("Loop for index "+index + " "+ upstreamValues + value);
2632                     var parent = parents[index];
2633                     if(parent instanceof F.Behavior){
2634                         if(upstreamValues[index]!=undefined){
2635                              //log("Sending Event "+upstreamValues[index]);
2636                             parent.sendEvent(upstreamValues[index]);
2637                             //log("Finished Sending Event");
2638                         }                
2639                         else{
2640                             //log("upstream value "+index+" is undefined"); 
2641                         }    
2642                     }
2643                     else{
2644                         log("Parent "+index+" is not a behaviour");
2645                     }
2646                 }
2647             }
2648             else{
2649                 log("Upstream transform returned wrong number of arguments was "+upstreamValues.length+" should be "+parents.length);        
2650             }
2651         }
2652         else{
2653             log("Upstream transformation returned undefined "+upstreamTransformation);        
2654         }
2655         behave.sendBehavior(value);            
2656     }
2657     else{
2658             event.sendEvent(value);
2659         }
2660         
2661             
2662     });
2663     
2664     this.sendEvent = function(message){
2665         upstreamEvent.sendEvent(message);
2666     }
2667 };
2668 
2669 /*var Behavior = function(eventStream, initialValue, downstreamTransformation, upstreamTransformation, parents){
2670     if (!(eventStream instanceof EventStream)) { 
2671         throw 'Behavior: expected event as second arg'; 
2672       }
2673       
2674       var behave = this;
2675       this.last = initialValue;
2676       this.stamp = 0;
2677 
2678 
2679     this.firedBefore = function(b2){
2680         return behave.stamp<b2.stamp;
2681     }
2682     this.firedAfter = function(b2){
2683         return behave.stamp>b2.stamp;
2684     }
2685  
2686     this.underlyingRaw = eventStream;
2687     this.underlying = createNode([eventStream], downstreamTransformation 
2688     ? function (p) {
2689         behave.stamp = p.stamp;
2690         //log("<updater1> "+p.value);
2691         behave.last = downstreamTransformation(p.value); 
2692 //log("</updater1> "+behave.last);
2693         p.value = behave.last; return p;
2694       } 
2695     : function (p) {
2696         //log("<updater2> "+p.value);
2697         behave.stamp = p.stamp;
2698         behave.last = p.value;
2699         //log("</updater2> "+p.value);
2700         return p
2701       });
2702       
2703     var upstreamEvent = receiverE(); 
2704     upstreamEvent.mapE(function(value){
2705     behave.last = value;
2706     if(upstreamTransformation!=undefined){
2707         var upstreamValues = upstreamTransformation(value);
2708         if(upstreamValues!=undefined){
2709             //log("upstreamValues Length: "+upstreamValues.length);
2710             //log(upstreamValues);
2711             if(upstreamValues.length==parents.length){
2712                 //log("Matching Return count");
2713                 for(index in parents){
2714                     //log("Loop for index "+index + " "+ upstreamValues + value);
2715                     var parent = parents[index];
2716                     if(parent instanceof Behavior){
2717                         if(upstreamValues[index]!=undefined){
2718                              //log("Sending Event "+upstreamValues[index]);
2719                             parent.sendEvent(upstreamValues[index]);
2720                             //log("Finished Sending Event");
2721                         }                
2722                         else{
2723                             //log("upstream value "+index+" is undefined"); 
2724                         }    
2725                     }
2726                     else{
2727                         log("Parent "+index+" is not a behaviour");
2728                     }
2729                 }
2730             }
2731             else{
2732                 log("Upstream transform returned wrong number of arguments was "+upstreamValues.length+" should be "+parents.length);        
2733             }
2734         }
2735         else{
2736             log("Upstream transformation returned undefined "+upstreamTransformation);        
2737         }
2738         behave.sendBehavior(value);            
2739     }
2740     else{
2741             eventStream.sendEvent(value);
2742         }
2743         
2744             
2745     });
2746     
2747     this.sendEvent = function(message){
2748         upstreamEvent.sendEvent(message);
2749     }
2750     this.valueNow = function(){
2751         return this.last;
2752     }
2753 }
2754 Behavior.prototype = new Object();*/
2755 
2756 
2757 
2758 
2759 
2760 
2761 F.Behavior.prototype.index = function(fieldName) {
2762   return this.liftB(function(obj) { return obj[fieldName]; });
2763 };
2764 
2765 /**
2766  * Creates an event stream that can be imperatively triggered with 
2767  * <code>sendEvent</code>.
2768  *
2769  * Useful for integrating Flapajx with callback-driven JavaScript code.
2770  */
2771 F.receiverE = function() {
2772   var evt = F.internal_.internalE();
2773   evt.sendEvent = function(value) {
2774     F.internal_.propagatePulse(new F.internal_.Pulse(F.internal_.nextStamp(), value),evt);
2775   };
2776   return evt;
2777 };
2778 
2779 //note that this creates a new timestamp and new event queue
2780 F.sendEvent = function (node, value) {
2781   if (!(node instanceof F.EventStream)) { throw 'sendEvent: expected Event as first arg'; } //SAFETY
2782   
2783   F.internal_.propagatePulse(new F.internal_.Pulse(F.internal_.nextStamp(), value),node);
2784 };
2785 
2786 // bindE :: F.EventStream a * (a -> F.EventStream b) -> F.EventStream b
2787 F.EventStream.prototype.bindE = function(k) {
2788   /* m.sendsTo resultE
2789    * resultE.sendsTo prevE
2790    * prevE.sendsTo returnE
2791    */
2792   var m = this;
2793   var prevE = false;
2794   
2795   var outE = new F.EventStream([],function(pulse) { return pulse; });
2796   outE.name = "bind outE";
2797   
2798   var inE = new F.EventStream([m], function (pulse) {
2799     if (prevE) {
2800       prevE.removeListener(outE, true);
2801       
2802     }
2803     prevE = k(pulse.value);
2804     if (prevE instanceof F.EventStream) {
2805       prevE.attachListener(outE);
2806     }
2807     else {
2808       throw "bindE : expected F.EventStream";
2809     }
2810 
2811     return F.doNotPropagate;
2812   });
2813   inE.name = "bind inE";
2814   
2815   return outE;
2816 };
2817 
2818 /**
2819  * @param {function(*):*} f
2820  * @returns {!F.EventStream}
2821  */
2822 F.EventStream.prototype.mapE = function(f) {
2823   if (!(f instanceof Function)) {
2824     throw ('mapE : expected a function as the first argument; received ' + f);
2825   };
2826   
2827   return new F.EventStream([this],function(pulse) {
2828     pulse.value = f(pulse.value);
2829     return pulse;
2830   });
2831 };
2832 
2833 /**
2834  * @returns {F.EventStream}
2835  */
2836 F.EventStream.prototype.notE = function() { 
2837   return this.mapE(function(v) { 
2838     return !v; 
2839   }); 
2840 };
2841 
2842 /**
2843  * Only produces events that match the given predicate.
2844  *
2845  * @param {function(*):boolean} pred
2846  * @returns {F.EventStream}
2847  */
2848 F.EventStream.prototype.filterE = function(pred) {
2849   if (!(pred instanceof Function)) {
2850     throw ('filterE : expected predicate; received ' + pred);
2851   };
2852   
2853   // Can be a bindE
2854   return new F.EventStream([this], function(pulse) {
2855     return pred(pulse.value) ? pulse : F.doNotPropagate;
2856   });
2857 };
2858 
2859 /**
2860  * Only triggers on the first event on this event stream.
2861  *
2862  * @returns {F.EventStream}
2863  */
2864 F.EventStream.prototype.onceE = function() {
2865   var done = false;
2866   return this.filterE(function(_) {
2867     if (!done) {
2868       done = true;
2869       return true;
2870     }
2871     return false;
2872   });
2873 };
2874 
2875 /**
2876  * Does not trigger on the first event on this event stream.
2877  *
2878  * @returns {F.EventStream}
2879  */
2880 F.EventStream.prototype.skipFirstE = function() {
2881   var skipped = false;
2882   return this.filterE(function(_) {
2883     if (!skipped) {
2884       skipped = true;
2885       return false;
2886     }
2887     return true;
2888   });
2889 };
2890 
2891 /**
2892  * Transforms this event stream to produce the result accumulated by
2893  * <code>combine</code>.
2894  *
2895  * <p>The following example accumulates a list of values with the latest
2896  * at the head:</p>
2897  *
2898  * @example
2899  * original.collectE([],function(new,arr) { return [new].concat(arr); });
2900  *
2901  * @param {*} init
2902  * @param {Function} combine <code>combine(acc, val)</code> 
2903  * @returns {F.EventStream}
2904  */
2905 F.EventStream.prototype.collectE = function(init, combine) {
2906   var acc = init;
2907   return this.mapE(
2908     function (n) {
2909       var next = combine(n, acc);
2910       acc = next;
2911       return next;
2912     });
2913 };
2914 
2915 /**
2916  * Given a stream of event streams, fires events from the most recent event
2917  * stream.
2918  * 
2919  * @returns {F.EventStream}
2920  */
2921 F.EventStream.prototype.switchE = function() {
2922   return this.bindE(function(v) { return v; });
2923 };
2924 
2925 F.recE = function(fn) {
2926   var inE = F.receiverE(); 
2927   var outE = fn(inE); 
2928   outE.mapE(function(x) { 
2929     inE.sendEvent(x); }); 
2930   return outE; 
2931 };
2932 
2933 F.internal_.delayStaticE = function (event, time) {
2934   
2935   var resE = F.internal_.internalE();
2936   
2937   new F.EventStream([event], function (p) { 
2938     setTimeout(function () { F.sendEvent(resE, p.value);},  time ); 
2939     return F.doNotPropagate;
2940   });
2941   
2942   return resE;
2943 };
2944 
2945 /**
2946  * Propagates signals from this event stream after <code>time</code>
2947  * milliseconds.
2948  * 
2949  * @param {F.Behavior|number} time
2950  * @returns {F.EventStream}
2951  */
2952 F.EventStream.prototype.delayE = function (time) {
2953   var event = this;
2954   
2955   if (time instanceof F.Behavior) {
2956     
2957     var receiverEE = F.internal_.internalE();
2958     var link = 
2959     {
2960       from: event, 
2961       towards: F.internal_.delayStaticE(event, time.valueNow())
2962     };
2963     
2964     //TODO: Change semantics such that we are always guaranteed to get an event going out?
2965     var switcherE = 
2966     new F.EventStream(
2967       [time.changes()],
2968       function (p) {
2969         link.from.removeListener(link.towards); 
2970         link =
2971         {
2972           from: event, 
2973           towards: F.internal_.delayStaticE(event, p.value)
2974         };
2975         F.sendEvent(receiverEE, link.towards);
2976         return F.doNotPropagate;
2977       });
2978     
2979     var resE = receiverEE.switchE();
2980     
2981     F.sendEvent(switcherE, time.valueNow());
2982     return resE;
2983     
2984       } else { return F.internal_.delayStaticE(event, time); }
2985 };
2986 
2987 //mapE: ([Event] (. Array a -> b)) . Array [Event] a -> [Event] b
2988 F.mapE = function (fn /*, [node0 | val0], ...*/) {
2989   //      if (!(fn instanceof Function)) { throw 'mapE: expected fn as second arg'; } //SAFETY
2990   
2991   var valsOrNodes = F.mkArray(arguments);
2992   //selectors[i]() returns either the node or real val, optimize real vals
2993   var selectors = [];
2994   var selectI = 0;
2995   var nodes = [];
2996   for (var i = 0; i < valsOrNodes.length; i++) {
2997     if (valsOrNodes[i] instanceof F.EventStream) {
2998       nodes.push(valsOrNodes[i]);
2999       selectors.push( 
3000         (function(ii) {
3001             return function(realArgs) { 
3002               return realArgs[ii];
3003             };
3004         })(selectI));
3005       selectI++;
3006     } else {
3007       selectors.push( 
3008         (function(aa) { 
3009             return function () {
3010               return aa;
3011             }; 
3012         })(valsOrNodes[i]));
3013     } 
3014   }
3015   
3016   var nofnodes = selectors.slice(1);
3017   
3018   if (nodes.length === 0) {
3019     return F.oneE(fn.apply(null, valsOrNodes));
3020   } else if ((nodes.length === 1) && (fn instanceof Function)) {
3021     return nodes[0].mapE(
3022       function () {
3023         var args = arguments;
3024         return fn.apply(
3025           null, 
3026           nofnodes.map(function (s) {return s(args);}));
3027       });
3028   } else if (nodes.length === 1) {
3029     return fn.mapE(
3030       function (v) {
3031         var args = arguments;
3032         return v.apply(
3033           null, 
3034           nofnodes.map(function (s) {return s(args);}));
3035       });                
3036   }
3037   else {
3038   throw 'unknown mapE case';
3039   }
3040 };
3041 
3042 /** 
3043  * Produces values from <i>valueB</i>, which are sampled when <i>sourceE</i>
3044  * is triggered.
3045  *
3046  * @param {F.Behavior} valueB
3047  * @returns {F.EventStream}
3048  */
3049 F.EventStream.prototype.snapshotE = function (valueB) {
3050   return new F.EventStream([this], function (pulse) {
3051     pulse.value = valueB.valueNow(); // TODO: glitch
3052     return pulse;
3053   });
3054 };
3055 
3056 /**
3057  * Filters out repeated events that are equal (JavaScript's <code>===</code>).
3058  *
3059  * @param {*=} optStart initial value (optional)
3060  * @returns {F.EventStream}
3061  */
3062 F.EventStream.prototype.filterRepeatsE = function(optStart) {
3063   var hadFirst = optStart === undefined ? false : true;
3064   var prev = optStart;
3065 
3066   return this.filterE(function (v) {
3067     if(typeof(v)=='object'){
3068         if(!objectEquals(v, prev)){
3069             prev = clone(v);
3070             return true;
3071         }
3072     }
3073     else if (!hadFirst || prev !== v) {
3074       hadFirst = true;
3075       prev = v;
3076       return true;
3077     }
3078     return false;
3079   });
3080 };
3081 
3082 /**
3083  * <i>Calms</i> this event stream to fire at most once every <i>time</i> ms.
3084  *
3085  * Events that occur sooner are delayed to occur <i>time</i> milliseconds after
3086  * the most recently-fired event.  Only the  most recent event is delayed.  So,
3087  * if multiple events fire within <i>time</i>, only the last event will be
3088  * propagated.
3089  *
3090  * @param {!number|F.Behavior} time
3091  * @returns {F.EventStream}
3092  */
3093 F.EventStream.prototype.calmE = function(time) {
3094   if (!(time instanceof F.Behavior)) {
3095     time = F.constantB(time);
3096   }
3097 
3098   var out = F.internal_.internalE();
3099   new F.EventStream(
3100     [this],
3101     function() {
3102       var towards = null;
3103       return function (p) {
3104         if (towards !== null) { clearTimeout(towards); }
3105         towards = setTimeout( function () { 
3106             towards = null;
3107             F.sendEvent(out,p.value); }, time.valueNow());
3108         return F.doNotPropagate;
3109       };
3110     }());
3111   return out;
3112 };
3113 
3114 /**
3115  * Only triggers at most every <code>time</code> milliseconds. Higher-frequency
3116  * events are thus ignored.
3117  *
3118  * @param {!number|F.Behavior} time
3119  * @returns {F.EventStream}
3120  */
3121 F.EventStream.prototype.blindE = function (time) {
3122   return new F.EventStream(
3123     [this],
3124     function () {
3125       var intervalFn = 
3126       time instanceof F.Behavior?
3127       function () { return time.valueNow(); }
3128       : function () { return time; };
3129       var lastSent = (new Date()).getTime() - intervalFn() - 1;
3130       return function (p) {
3131         var curTime = (new Date()).getTime();
3132         if (curTime - lastSent > intervalFn()) {
3133           lastSent = curTime;
3134           return p;
3135         }
3136         else { return F.doNotPropagate; }
3137       };
3138     }());
3139 };
3140 
3141 /**
3142  * @param {*} init
3143  * @returns {!F.Behavior}
3144  */
3145 F.EventStream.prototype.startsWith = function(init) {
3146   return new F.Behavior(this,init);
3147 };
3148 
3149 /**
3150  * Returns the presently stored value.
3151  */
3152 F.Behavior.prototype.valueNow = function() {
3153   return this.last;
3154 };
3155 
3156 /**
3157  * @returns {F.EventStream}
3158  */
3159 F.Behavior.prototype.changes = function() {
3160   return this.underlying;
3161 };
3162 
3163 /**
3164  * @returns {F.Behavior}
3165  */
3166 F.Behavior.prototype.firedBefore = function(b2) {
3167   return this.stamp<b2.stamp;
3168 };
3169 
3170 
3171 /**
3172  * @returns {F.Behavior}
3173  */
3174 F.Behavior.prototype.firedAfter = function(b2) {
3175   return this.stamp>b2.stamp;  
3176 };
3177 
3178 /**
3179  * @returns {!F.Behavior}
3180  */
3181 F.Behavior.prototype.switchB = function() {
3182   var behaviourCreatorsB = this;
3183   var init = behaviourCreatorsB.valueNow();
3184   
3185   var prevSourceE = null;
3186   
3187   var receiverE = F.internal_.internalE();
3188   
3189   //XXX could result in out-of-order propagation! Fix!
3190   var makerE = 
3191   new F.EventStream(
3192     [behaviourCreatorsB.changes()],
3193     function (p) {
3194       if (!(p.value instanceof F.Behavior)) { throw 'switchB: expected F.Behavior as value of F.Behavior of first argument'; } //SAFETY
3195       if (prevSourceE != null) {
3196         prevSourceE.removeListener(receiverE);
3197       }
3198       
3199       prevSourceE = p.value.changes();
3200       prevSourceE.attachListener(receiverE);
3201       
3202       F.sendEvent(receiverE, p.value.valueNow());
3203       return F.doNotPropagate;
3204     });
3205   
3206   if (init instanceof F.Behavior) {
3207     F.sendEvent(makerE, init);
3208   }
3209   
3210   return receiverE.startsWith(init instanceof F.Behavior? init.valueNow() : init);
3211 };
3212 
3213 /**
3214  * @param {!F.Behavior|number} interval
3215  * @returns {F.Behavior}
3216  */
3217 F.timerB = function(interval) {
3218   return F.timerE(interval).startsWith((new Date()).getTime());
3219 };
3220 
3221 //TODO test, signature
3222 F.Behavior.prototype.delayB = function (time, init) {
3223   var triggerB = this;
3224   if (!(time instanceof F.Behavior)) {
3225     time = F.constantB(time);
3226   }
3227   return triggerB.changes()
3228            .delayE(time)
3229            .startsWith(arguments.length > 3 ? init : triggerB.valueNow());
3230 };
3231 
3232 //artificially send a pulse to underlying event node of a behaviour
3233 //note: in use, might want to use a receiver node as a proxy or an identity map
3234 F.Behavior.prototype.sendBehavior = function(val) {
3235   F.sendEvent(this.underlyingRaw,val);
3236 };
3237 
3238 F.Behavior.prototype.ifB = function(trueB,falseB) {
3239   var testB = this;
3240   //TODO auto conversion for behaviour funcs
3241   if (!(trueB instanceof F.Behavior)) { trueB = F.constantB(trueB); }
3242   if (!(falseB instanceof F.Behavior)) { falseB = F.constantB(falseB); }
3243   return F.liftB(function(te,t,f) { return te ? t : f; },testB,trueB,falseB);
3244 };
3245 
3246 F.ifB = function(test,cons,altr) {
3247   if (!(test instanceof F.Behavior)) { test = F.constantB(test); };
3248   
3249   return test.ifB(cons,altr);
3250 };
3251 
3252 
3253 /** 
3254  * condB: . [F.Behavior boolean, F.Behavior a] -> F.Behavior a
3255  * 
3256  * Evaluates to the first <i>resultB</i> whose associated <i>conditionB</i> is
3257  * <code>True</code>
3258  *
3259  * @param {Array.<Array.<F.Behavior>>} var_args
3260  * @returns {F.Behavior}
3261  */
3262 F.condB = function (var_args ) {
3263   var pairs = F.mkArray(arguments);
3264 return F.liftB.apply({},[function() {
3265     for(var i=0;i<pairs.length;i++) {
3266       if(arguments[i]) return arguments[pairs.length+i];
3267     }
3268     return undefined;
3269   }].concat(pairs.map(function(pair) {return pair[0];})
3270             .concat(pairs.map(function(pair) {return pair[1];}))));
3271 };
3272 
3273 /**
3274  * @param {*} val
3275  * @returns {!F.Behavior.<*>}
3276  */
3277 F.constantB = function (val) {
3278   return new F.Behavior(F.internal_.internalE(), val);
3279 };
3280 
3281 /**
3282  * @param {Function|F.Behavior} fn
3283  * @param {...F.Behavior} var_args
3284  * @returns !F.Behavior            
3285  */
3286 F.liftB = function (fn) {
3287    // showObj(var_args);
3288   var args = Array.prototype.slice.call(arguments, 1);
3289   //dependencies
3290   var constituentsE = F.map(function (b) { return b.changes(); }, F.filter(function (v) { return v instanceof F.Behavior; }, F.mkArray(arguments)));
3291   
3292   //calculate new vals
3293   var getCur = function (v) {
3294     return v instanceof F.Behavior ? v.last : v;
3295   };
3296   
3297   var getRes = function () {
3298     return getCur(fn).apply(null, F.map(getCur, args));
3299   };
3300 
3301   if(constituentsE.length === 1) {
3302     return new F.Behavior(constituentsE[0],getRes(),getRes);
3303   }
3304     
3305   //gen/send vals @ appropriate time
3306   var prevStamp = -1;
3307   var mid = new F.EventStream(constituentsE, function (p) {
3308     if (p.stamp != prevStamp) {
3309       prevStamp = p.stamp;
3310       return p; 
3311     }
3312     else {
3313       return F.doNotPropagate;
3314     }
3315   });
3316   
3317   return new F.Behavior(mid,getRes(),getRes);
3318 };   
3319   
3320   
3321   /**
3322  * @param {Function|F.Behavior} fn
3323  * @param {Function|F.Behavior} fu
3324  * @param {...F.Behavior} var_args
3325  * @returns !F.Behavior            
3326  */
3327 F.liftBI = function (fn, functionUp) {
3328    // showObj(var_args);
3329   var args = Array.prototype.slice.call(arguments, 2);
3330   //dependencies
3331   var constituentsE = F.map(function (b) { return b.changes(); }, F.filter(function (v) { return v instanceof F.Behavior; }, F.mkArray(arguments)));
3332   
3333   //calculate new vals
3334   var getCur = function (v) {
3335     return v instanceof F.Behavior ? v.last : v;
3336   };
3337   
3338   var getRes = function () {
3339     return getCur(fn).apply(null, F.map(getCur, args));
3340   };
3341 
3342   if(constituentsE.length === 1) {
3343     return new F.Behavior(constituentsE[0],getRes(),getRes, functionUp, args);
3344   }
3345     
3346   //gen/send vals @ appropriate time
3347   var prevStamp = -1;
3348   var mid = new F.EventStream(constituentsE, function (p) {
3349     if (p.stamp != prevStamp) {
3350       prevStamp = p.stamp;
3351       return p; 
3352     }
3353     else {
3354       return F.doNotPropagate;
3355     }
3356   });
3357   
3358   return new F.Behavior(mid,getRes(),getRes, functionUp, args);
3359 };           
3360 /*F.liftBI = function (functionDown, functionUp, parents) {
3361       //var parents = Array.slice(arguments, 2);
3362     args = parents; 
3363     //dependencies
3364       var constituentsE =
3365         map(changes,
3366         filter(function (v) { return v instanceof F.Behavior; },
3367                 parents));
3368                 
3369       var constituentsE =
3370     F.mkArray(arguments)
3371     .filter(function (v) { return v instanceof F.Behavior; })
3372     .map(function (b) { return b.changes(); });   
3373       
3374       //calculate new vals
3375       var getCur = function (v) {
3376         return v instanceof F.Behavior ? v.last : v;
3377       };
3378       
3379       var ctx = this;
3380       var getRes = function () {
3381         return getCur(functionDown).apply(ctx, map(getCur, parents));
3382       };
3383 
3384       if(constituentsE.length == 1) {
3385         return new F.Behavior(constituentsE[0],getRes(),getRes, functionUp, parents);
3386       }
3387         
3388       //gen/send vals @ appropriate time
3389       var prevStamp = -1;
3390       var mid = createNode(constituentsE, function (p) {
3391         if (p.stamp != prevStamp) {
3392           prevStamp = p.stamp;
3393           return p; 
3394         }
3395         else {
3396           return doNotPropagate;
3397         }
3398       });
3399       //log("Behaviour with multiple parents detected");
3400       return new F.Behavior(mid,getRes(),getRes, functionUp, parents);
3401     };
3402 
3403     F.Behavior.prototype.liftBI = function(functionDown, functionUp, parents) {        
3404         return F.liftBI.apply(this,[functionDown, functionUp].concat([this]).concat(parents));
3405     };            */
3406 
3407 
3408 
3409 /**
3410  * @param {...F.Behavior} var_args
3411  * @returns {F.Behavior}
3412  */
3413 F.Behavior.prototype.ap = function(var_args) {
3414   var args = [this].concat(F.mkArray(arguments));
3415   return F.liftB.apply(null, args);
3416 };
3417 
3418 /**
3419  * @param {F.Behavior|Function} fn
3420  * @returns {!F.Behavior}
3421  */
3422 F.Behavior.prototype.liftB = function(fn) {
3423   return F.liftB(fn, this);
3424 };
3425 
3426 /**
3427  * @param {...F.Behavior} var_args
3428  */
3429 F.Behavior.andB = function (var_args) {
3430 return F.liftB.apply({},[function() {
3431     for(var i=0; i<arguments.length; i++) {if(!arguments[i]) return false;}
3432     return true;
3433 }].concat(F.mkArray(arguments)));
3434 };    
3435 F.andB = F.Behavior.andB;    
3436 /**
3437  * @param {...F.Behavior} var_args
3438  */
3439 F.Behavior.orB = function (var_args) {
3440   return F.liftB.apply({},[function() {
3441       for(var i=0; i<arguments.length; i++) {if(arguments[i]) return true;}
3442       return false;
3443   }].concat(F.mkArray(arguments)));
3444 };
3445 F.orB = F.Behavior.orB;
3446 //F.orB = F.Behavior.orB;
3447 
3448 /**
3449  * @returns {F.Behavior}
3450  */
3451 F.Behavior.prototype.notB = function() {
3452   return this.liftB(function(v) { return !v; });
3453 };
3454 F.notB = F.Behavior.prototype.notB;
3455 
3456 F.Behavior.prototype.blindB = function (intervalB) {
3457   return this.changes().blindE(intervalB).startsWith(this.valueNow());
3458 };
3459 
3460 F.Behavior.prototype.calmB = function (intervalB) {
3461   return this.changes().calmE(intervalB).startsWith(this.valueNow());
3462 };
3463 
3464 ///////////////////////////////////////////////////////////////////////////////
3465 // DOM Utilities
3466 
3467 /**
3468  * assumes IDs already preserved
3469  *
3470  * @param {Node|string} replaceMe
3471  * @param {Node|string} withMe
3472  * @returns {Node}
3473  */
3474 F.dom_.swapDom = function(replaceMe, withMe) {
3475   if ((replaceMe === null) || (replaceMe === undefined)) { throw ('swapDom: expected dom node or id, received: ' + replaceMe); } //SAFETY
3476   
3477   var replaceMeD = F.dom_.getObj(replaceMe);
3478   if (!(replaceMeD.nodeType > 0)) { throw ('swapDom expected a Dom node as first arg, received ' + replaceMeD); } //SAFETY
3479   
3480   if (withMe) {
3481     var withMeD = F.dom_.getObj(withMe);
3482     if (!(withMeD.nodeType > 0)) { throw 'swapDom: can only swap with a DOM object'; } //SAFETY
3483     try {
3484       if (replaceMeD.parentNode === null) { return withMeD; }
3485       if(withMeD != replaceMeD) replaceMeD.parentNode.replaceChild(withMeD, replaceMeD);
3486     } catch (e) {
3487       throw('swapDom error in replace call: withMeD: ' + withMeD + ', replaceMe Parent: ' + replaceMeD + ', ' + e + ', parent: ' + replaceMeD.parentNode);                    
3488     }
3489   } else {
3490     replaceMeD.parentNode.removeChild(replaceMeD); //TODO isolate child and set innerHTML to "" to avoid psuedo-leaks?
3491   }
3492   return replaceMeD;
3493 };
3494 
3495 //getObj: String U Dom -> Dom
3496 //throws 
3497 //  'getObj: expects a Dom obj or Dom id as first arg'
3498 //  'getObj: flapjax: cannot access object'
3499 //  'getObj: no obj to get
3500 //also known as '$'
3501 F.dom_.getObj = function (name) {
3502   if (typeof(name) === 'object') { return name; }
3503   else if ((typeof(name) === 'null') || (typeof(name) === 'undefined')) {
3504     throw 'getObj: expects a Dom obj or Dom id as first arg';
3505   } else {
3506     
3507     var res = 
3508     document.getElementById ? document.getElementById(name) :
3509     document.all ? document.all[name] :
3510     document.layers ? document.layers[name] :
3511     (function(){ throw 'getObj: flapjax: cannot access object';})();
3512     if ((res === null) || (res === undefined)) { 
3513       throw ('getObj: no obj to get: ' + name); 
3514     }
3515     return res;
3516   }
3517 };
3518 
3519 // TODO: should be richer
3520 F.$ = F.dom_.getObj;
3521 
3522 /**
3523  * helper to reduce obj look ups
3524  * getDynObj: domNode . Array (id) -> domObj
3525  * obj * [] ->  obj
3526  * obj * ['position'] ->  obj
3527  * obj * ['style', 'color'] ->  obj.style
3528  *
3529  * @param {Node|string} domObj
3530  * @param {Array.<string>} indices
3531  * @returns {Object}
3532  */
3533 F.dom_.getMostDom = function (domObj, indices) {
3534   var acc = F.dom_.getObj(domObj);
3535   if ( (indices === null) || (indices === undefined) || (indices.length < 1)) {
3536     return acc;
3537   } else {
3538     for (var i = 0; i < indices.length - 1; i++) {
3539       acc = acc[indices[i]];
3540     }
3541     return acc;
3542   }       
3543 };
3544 
3545 F.dom_.getDomVal = function (domObj, indices) {
3546   var val = F.dom_.getMostDom(domObj, indices);
3547   if (indices && indices.length > 0) {
3548     val = val[indices[indices.length - 1]];
3549   }
3550   return val;
3551 };
3552 
3553 /**
3554  * An event stream that fires every <code>intervalB</code> ms.
3555  *
3556  * The interval itself may be time-varying. The signal carried is the current
3557  * time, in milliseconds.
3558  *
3559  * @param {!F.Behavior|number} intervalB
3560  * @returns {F.EventStream}
3561  */
3562 F.timerE = function(intervalB) {
3563   if (!(intervalB instanceof F.Behavior)) {
3564     intervalB = F.constantB(intervalB);
3565   }
3566   var eventStream = F.receiverE();
3567   var callback = function() {
3568     eventStream.sendEvent((new Date()).getTime());
3569   };
3570   var timerID = null;
3571   intervalB.liftB(function(interval) {
3572     if (timerID) {
3573       clearInterval(timerID);
3574       timerID = null;
3575     }
3576     if (typeof interval === 'number' && interval > 0) {
3577       timerID =  setInterval(callback, interval);
3578     }
3579   });
3580   return eventStream;
3581 };
3582 
3583 
3584 // Applies f to each element of a nested array.
3585 F.dom_.deepEach = function(arr, f) {
3586   for (var i = 0; i < arr.length; i++) {
3587     if (arr[i] instanceof Array) {
3588       F.dom_.deepEach(arr[i], f);
3589     }
3590     else {
3591       f(arr[i]);
3592     }
3593   }
3594 };
3595 
3596 
3597 F.dom_.mapWithKeys = function(obj, f) {
3598   for (var ix in obj) {
3599     if (!(Object.prototype && Object.prototype[ix] === obj[ix])) {
3600       f(ix, obj[ix]);
3601     }
3602   }
3603 };
3604 
3605 
3606 /**
3607  * @param {Node} parent
3608  * @param {Node} newChild
3609  * @param {Node} refChild
3610  */
3611 F.dom_.insertAfter = function(parent, newChild, refChild) {
3612   if (typeof refChild != "undefined" && refChild.nextSibling) {
3613     parent.insertBefore(newChild, refChild.nextSibling);
3614   }
3615   else {
3616     // refChild == parent.lastChild
3617     parent.appendChild(newChild);
3618   }
3619 };
3620 
3621 /**
3622  * @param {Node} parent
3623  * @param {Array.<Node>} existingChildren
3624  * @param {Array.<Node>} newChildren
3625  */
3626 F.dom_.swapChildren = function(parent, existingChildren, newChildren) {
3627   var end = Math.min(existingChildren.length, newChildren.length);
3628   var i;
3629 
3630   for (i = 0; i < end; i++) {
3631     parent.replaceChild(newChildren[i], existingChildren[i]);
3632   }
3633 
3634   var lastInsertedChild = existingChildren[i - 1];
3635 
3636   if (end < existingChildren.length) {
3637     for (i = end; i < existingChildren.length; i++) {
3638       parent.removeChild(existingChildren[i]);
3639     }
3640   }
3641   else if (end < newChildren.length) {
3642     for (i = end; i < newChildren.length; i++) {
3643       F.dom_.insertAfter(parent, newChildren[i], newChildren[i - 1]);
3644     }
3645   }
3646 };
3647 
3648 /**
3649  * not a word
3650  *
3651  * @param {*} maybeElement
3652  * @returns {Node}
3653  *
3654  * @suppress {checkTypes} the nodeType check does not get by the typechecker
3655  */
3656 F.dom_.elementize = function(maybeElement) {
3657   return (maybeElement.nodeType > 0) 
3658            ? maybeElement
3659            : document.createTextNode(maybeElement.toString()); // TODO: toString!!
3660 };
3661 
3662 
3663 /**
3664  * @param {Object} obj
3665  * @param {string} prop
3666  * @param {*} val
3667  */
3668 F.dom_.staticEnstyle = function(obj, prop, val) {
3669   if (val instanceof Object) {
3670     // TODO: enstyle is missing? I think this should be staticEnstyle.
3671     // mapWithKeys(val, function(k, v) { enstyle(obj[prop], k, v); });
3672   }
3673   else {
3674     obj[prop] = val;
3675   }
3676 };
3677 
3678 
3679 /**
3680  * @param {Object} obj
3681  * @param {string} prop
3682  * @param {F.Behavior|*} val
3683  */
3684 F.dom_.dynamicEnstyle = function(obj, prop, val) {
3685 //alert(F.dom_);
3686   if (val instanceof F.Behavior) {
3687     // TODO: redundant? F.liftB will call anyway ...
3688     F.dom_.staticEnstyle(obj, prop, val.valueNow()); 
3689     val.liftB(function(v) {
3690       F.dom_.staticEnstyle(obj, prop, v);
3691     });
3692   }
3693   else if (val instanceof Object) {
3694     F.dom_.mapWithKeys(val, function(k, v) {
3695       F.dom_.dynamicEnstyle(obj[prop], k, v);
3696     });
3697   }
3698   else {
3699     obj[prop] = val;
3700   }
3701 };
3702   
3703 
3704 /**
3705  * @param {string} tagName
3706  * @returns {function((string|Object|Node)=, ...[(string|Node|Array.<Node>)]):!HTMLElement}
3707  */
3708 F.dom_.makeTagB = function(tagName) { return function() {
3709   var attribs, children;
3710 
3711   if (typeof(arguments[0]) === "object" && 
3712       !(arguments[0].nodeType > 0 || arguments[0] instanceof F.Behavior || 
3713         arguments[0] instanceof Array)) {
3714     attribs = arguments[0];
3715     children = Array.prototype.slice.call(arguments, 1);
3716   }
3717   else {
3718     attribs = { };
3719     children = F.mkArray(arguments);
3720   }
3721  
3722   var elt = document.createElement(tagName);
3723 
3724   F.dom_.mapWithKeys(attribs, function(name, val) {
3725     if (val instanceof F.Behavior) {
3726       elt[name] = val.valueNow();
3727       val.liftB(function(v) { 
3728         F.dom_.staticEnstyle(elt, name, v); });
3729     }
3730     else {
3731       F.dom_.dynamicEnstyle(elt, name, val);
3732     }
3733   });
3734 
3735   F.dom_.deepEach(children, function(child) {
3736     if (child instanceof F.Behavior) {
3737       var lastVal = child.valueNow();
3738       if (lastVal instanceof Array) {
3739         lastVal = lastVal.map(F.dom_.elementize);
3740         lastVal.forEach(function(dynChild) { elt.appendChild(dynChild); });
3741         child.liftB(function(currentVal) {
3742           currentVal = currentVal.map(F.dom_.elementize);
3743           F.dom_.swapChildren(elt, lastVal, currentVal);
3744           lastVal = currentVal;
3745         });
3746       }
3747       else {
3748         lastVal = F.dom_.elementize(lastVal);
3749         elt.appendChild(lastVal);
3750         var lastValIx = elt.childNodes.length - 1; 
3751         child.liftB(function(currentVal) {
3752           currentVal = F.dom_.elementize(currentVal);
3753           if (lastVal.parentNode != elt) {
3754             elt.appendChild(currentVal); }
3755           else {
3756             elt.replaceChild(currentVal, lastVal); }
3757           lastVal = currentVal;
3758         });
3759       }
3760     }
3761     else {
3762       elt.appendChild(F.dom_.elementize(child));
3763     }
3764   });
3765 
3766   return elt;
3767 }; };
3768 
3769 
3770 var dtypes = [ "a", "b", "blockquote", "br", "button", "canvas", "div", "fieldset", 
3771 "form", "font", "h1", "h2", "h3", "h4", "hr", "iframe", "input", 
3772 "label", "legend", "li", "ol", "optgroup", "option", 
3773 "p", "select", "span", "strong", "table", "tbody", 
3774 "td", "textarea", "tfoot", "th", "thead", "tr", "tt", "ul" ];
3775 
3776 for(index in dtypes){
3777     var name = dtypes[index];
3778     if(window&&typeof(name)=='string'&&window[name.toUpperCase()])
3779         window[name.toUpperCase()] = F.dom_.makeTagB(name);
3780 }
3781 
3782 /**
3783  * Creates a DOM element with time-varying children.
3784  *
3785  * @param {!string} tag
3786  * @param {!string|Object|Node=} opt_style
3787  * @param {...(string|Node|Array.<Node>|F.Behavior)} var_args
3788  * @returns {!HTMLElement}
3789  */
3790 F.elt = function(tag, opt_style, var_args) {
3791   return F.dom_.makeTagB(tag).apply(null, F.mkArray(arguments).slice(1));
3792 };
3793 
3794 //TEXTB: F.Behavior a -> F.Behavior Dom TextNode
3795 F.text = function (strB) {
3796 
3797   // TODO: Create a static textnode and set the data field?
3798   //      if (!(strB instanceof F.Behavior || typeof(strB) == 'string')) { throw 'TEXTB: expected F.Behavior as second arg'; } //SAFETY
3799   if (!(strB instanceof F.Behavior)) { strB = F.constantB(strB); }
3800   
3801   return strB.changes().mapE(
3802       function (txt) { return document.createTextNode(txt); })
3803     .startsWith(document.createTextNode(strB.valueNow()));
3804 };
3805 
3806 /**
3807  * @typedef {function((!string|Object|Node)=, ...[(!string|Node|Array.<Node>)]):!Node}
3808  */
3809 F.tagMaker;
3810 
3811 /** @type {F.tagMaker} */
3812 var DIV = F.dom_.makeTagB('div');
3813 /** @type {F.tagMaker} */
3814 var SPAN = F.dom_.makeTagB('span');
3815 /** @type {F.tagMaker} */
3816 var A = F.dom_.makeTagB('a');
3817 /** @type {F.tagMaker} */
3818 var TEXTAREA = F.dom_.makeTagB('TEXTAREA');
3819 /** @type {F.tagMaker} */
3820 var OPTION = F.dom_.makeTagB('OPTION');
3821 /** @type {F.tagMaker} */
3822 var INPUT = F.dom_.makeTagB('INPUT');
3823 /** @type {F.tagMaker} */
3824 var SELECT = F.dom_.makeTagB('SELECT');
3825 /** @type {F.tagMaker} */
3826 var IMG = F.dom_.makeTagB('IMG');
3827 /** @type {F.tagMaker} */
3828 var PRE = F.dom_.makeTagB('pre');
3829 
3830 
3831 var TEXT = function (str) {
3832   return document.createTextNode(str);
3833 };
3834 
3835 ///////////////////////////////////////////////////////////////////////////////
3836 // Reactive DOM
3837 
3838 /**
3839  * [EventName] * (F.EventStream DOMEvent, ... -> Element) -> Element
3840  *
3841 
3842  * <p>An element may be a function of some event and behaviours, while those
3843  * same events and behaviours might als be functions of the tag. <i>tagRec</i>
3844  * is a convenience method for writing such cyclic dependencies. Also, as
3845  * certain updates may cause a tag to be destroyed and recreated, this
3846  * guarentees the extracted events are for the most recently constructed DOM
3847  * node.</p>
3848  * 
3849  * <p>This example create a tags whose background color is white on mouse 
3850  * over and black on mouseout, starting as black.</p>
3851  *
3852  * @example
3853  * F.tagRec(
3854  *  ['mouseover', 'mouseout'],
3855  *  function (overE, outE) {
3856  *    return F.elt('div',
3857  *      { style: {
3858  *        color:
3859  *          mergeE(overE.constantE('#FFF'), outE.constantE('#000')).
3860  *          startsWith('#000')}},
3861  *      'mouse over me to change color!');
3862  *  });
3863  * 
3864  */
3865 F.tagRec = function (eventNames, maker) {
3866   if (!(eventNames instanceof Array)) { throw 'tagRec: expected array of event names as first arg'; } //SAFETY
3867   if (!(maker instanceof Function)) { throw 'tagRec: expected function as second arg'; } //SAFETY
3868   
3869   var numEvents = eventNames.length;
3870 
3871   var receivers = [ ];
3872   var i;
3873   for (i = 0; i < numEvents; i++) {
3874     receivers.push(F.internal_.internalE());
3875   }
3876 
3877   var elt = maker.apply(null, receivers);
3878 
3879   for (i = 0; i < numEvents; i++) {
3880     F.extractEventE(elt, eventNames[i]).attachListener(receivers[i]);
3881   }
3882 
3883   return elt;
3884 };
3885 
3886 F.dom_.extractEventDynamicE = function(eltB, eventName, useCapture) {
3887   if (typeof useCapture === 'undefined') {
3888     useCapture = false;
3889   }
3890   var eventStream = F.receiverE();
3891   var callback = function(evt) {
3892     eventStream.sendEvent(evt); 
3893   };
3894   var currentElt = false;
3895   eltB.liftB(function(elt) {
3896     if (currentElt) {
3897       currentElt.removeEventListener(eventName, callback, useCapture); 
3898     }
3899     currentElt = elt;
3900     if (elt && elt.addEventListener && elt.removeEventListener) {
3901       elt.addEventListener(eventName, callback, useCapture);
3902     }
3903   });
3904   return eventStream;
3905 };
3906 
3907 F.dom_.extractEventStaticE = function(elt, eventName, useCapture) {
3908   if (typeof useCapture === 'undefined') {
3909     useCapture = false;
3910   }
3911   var eventStream = F.receiverE();
3912   var callback = function(evt) {
3913     eventStream.sendEvent(evt); 
3914   };
3915   if(elt.addEventListener){
3916     elt.addEventListener(eventName, callback, useCapture);
3917   }
3918   else{
3919     elt.attachEvent("on"+eventName, callback);
3920   }
3921   return eventStream;  
3922 };
3923 
3924 /**
3925  * A signal carrying DOM events, which triggers on each event.
3926  * 
3927  * The argument <code>elt</code> may be a behavior of DOM nodes or 
3928  * <code>false</code>.
3929  * 
3930  * @param {F.Behavior|Node|Window} elt
3931  * @param {string} eventName
3932  * @param {boolean=} useCapture
3933  * @returns {F.EventStream}
3934  */
3935 F.extractEventE = function(elt, eventName, useCapture) {
3936   if (elt instanceof F.Behavior) {
3937     return F.dom_.extractEventDynamicE(elt, eventName, useCapture);
3938   }
3939   else {
3940     if(typeof(elt)=="string"){
3941         elt = document.getElementById(elt);
3942     }
3943     return F.dom_.extractEventStaticE(elt, eventName, useCapture);
3944   }
3945 };
3946 
3947 /**
3948  *
3949  * Extracts just one event from elt.
3950  *
3951  * oneEvent detaches the underlying DOM callback after receiving the event.
3952  *
3953  * @param {Node} elt
3954  * @param {string} eventName
3955  * @returns {F.EventStream}
3956  */
3957 F.oneEvent = function(elt, eventName) {
3958   return F.recE(function(evts) {
3959     return F.extractEventE(evts.constantE(false).startsWith(elt),
3960       eventName);
3961   });
3962 };
3963 
3964 /**
3965  * @param {F.Behavior} domObj
3966  * @param {...string} var_args
3967  * @returns {F.EventStream}
3968  */
3969 F.extractEventsE = function (domObj, var_args) {
3970     var eventNames = Array.prototype.slice.call(arguments, 1);
3971     var events = (eventNames.length === 0 ? [] : eventNames).map(function (eventName) {
3972         return F.extractEventE(domObj, eventName);
3973     });
3974     return F.mergeE.apply(null, events);
3975 };
3976 
3977 /**extractDomFieldOnEventE: Event * Dom U String . Array String -> Event a
3978  *
3979  * @param {F.EventStream} triggerE
3980  * @param {Node} domObj
3981  * @param {...*} var_args
3982  */
3983 F.extractDomFieldOnEventE = function (triggerE, domObj, var_args) {
3984   if (!(triggerE instanceof F.EventStream)) { throw 'extractDomFieldOnEventE: expected Event as first arg'; } //SAFETY
3985   var indices = Array.prototype.slice.call(arguments, 2);
3986   var res =
3987   triggerE.mapE(
3988     function () { return F.dom_.getDomVal(domObj, indices); });
3989   return res;
3990 };
3991 
3992 F.extractValueE = function (domObj) {
3993   return F.extractValueB.apply(null, arguments).changes();
3994 };
3995 
3996 //extractValueOnEventB: Event * DOM -> F.Behavior
3997 // value of a dom form object, polled during trigger
3998 F.extractValueOnEventB = function (triggerE, domObj) {
3999   return F.dom_.extractValueStaticB(domObj, triggerE);
4000 };
4001 
4002 /**
4003  * If no trigger for extraction is specified, guess one
4004  *
4005  * @param {Node} domObj
4006  * @param {F.EventStream=} triggerE
4007  * @returns {!F.Behavior}
4008  */
4009 F.dom_.extractValueStaticB = function (domObj, triggerE) { 
4010   var objD;
4011   try {
4012     objD = F.dom_.getObj(domObj);
4013     //This is for IE
4014     if(typeof(domObj) === 'string' && objD.id != domObj) {
4015       throw 'Make a radio group';
4016     }
4017   } catch (e) {
4018     objD = {type: 'radio-group', name: domObj};
4019   }
4020   
4021   var getter; // get value at any current point in time
4022   
4023   var result;
4024 
4025   switch (objD.type)  {
4026     //TODO: checkbox.value instead of status?
4027   case 'checkbox': 
4028     result = F.extractDomFieldOnEventE(
4029           triggerE ? triggerE : 
4030           F.extractEventsE(
4031             objD, 
4032             'click', 'keyup', 'change'),
4033           objD,
4034           'checked').filterRepeatsE(objD.checked).startsWith(objD.checked);
4035     break; 
4036   case 'select-one':
4037       getter = function () {                         
4038         return objD.selectedIndex > -1 ? 
4039         (objD.options[objD.selectedIndex].value ?
4040           objD.options[objD.selectedIndex].value :
4041           objD.options[objD.selectedIndex].innerText)
4042         : undefined;
4043       };
4044       result = (triggerE ? triggerE :
4045             F.extractEventsE(
4046               objD,
4047               'click', 'keyup', 'change')).mapE(getter).filterRepeatsE().startsWith(getter());
4048       break;
4049   case 'select-multiple':
4050     //TODO ryan's cfilter adapted for equality check
4051     getter = function () {
4052       var res = [];
4053       for (var i = 0; i < objD.options.length; i++) {
4054         if (objD.options[i].selected) {
4055           res.push(objD.options[i].value ? objD.options[i].value : objD.options[i].innerText);
4056         }
4057       }
4058       return res;
4059     };
4060     result = 
4061         (triggerE ? triggerE : 
4062         F.extractEventsE(
4063           objD,
4064           'click', 'keyup', 'change')).mapE(getter).startsWith(getter());
4065     break;
4066     
4067   case 'text':
4068   case 'textarea':
4069   case 'hidden':
4070   case 'password':
4071     result = F.extractDomFieldOnEventE(
4072           triggerE ? triggerE :
4073           F.extractEventsE(
4074             objD, 
4075             'click', 'keyup', 'change'),
4076           objD,
4077           'value').filterRepeatsE(objD.value).startsWith(objD.value);
4078     break;
4079     
4080   case 'button': //same as above, but don't filter repeats
4081     result = F.extractDomFieldOnEventE(
4082         triggerE ? triggerE :
4083         F.extractEventsE(
4084           objD, 
4085           'click', 'keyup', 'change'),
4086         objD,
4087         'value').startsWith(objD.value);
4088     break;
4089     
4090   case 'radio': 
4091   case 'radio-group':
4092     
4093     //TODO returns value of selected button, but if none specified,
4094     //      returns 'on', which is ambiguous. could return index,
4095     //      but that is probably more annoying
4096     
4097     var radiosAD = 
4098       F.mkArray(document.getElementsByTagName('input'))
4099       .filter(
4100       function (elt) { 
4101         return (elt.type === 'radio') &&
4102         (elt.getAttribute('name') === objD.name); 
4103       });
4104     
4105     getter = 
4106     objD.type === 'radio' ?
4107     
4108     function () {
4109       return objD.checked;
4110     } :
4111     
4112     function () {
4113       for (var i = 0; i < radiosAD.length; i++) {
4114         if (radiosAD[i].checked) {
4115           return radiosAD[i].value; 
4116         }
4117       }
4118       return undefined; //TODO throw exn? 
4119     };
4120     
4121     var actualTriggerE = triggerE ? triggerE :
4122     F.mergeE.apply(
4123       null,
4124       radiosAD.map(
4125         function (radio) { 
4126           return F.extractEventsE(
4127             radio, 
4128         'click', 'keyup', 'change'); }));
4129     
4130     result =
4131       actualTriggerE.mapE(getter).filterRepeatsE(getter()).startsWith(getter());
4132     break;
4133   default:
4134     throw ('extractValueStaticB: unknown value type "' + objD.type + '"');
4135   }
4136 
4137   return result;
4138 };
4139 
4140 /**
4141  * Signal carries the value of the form element <code>domObj</code>.
4142  *
4143  * The signal triggers when a change event fires, which depends on the
4144  * type of <code>domObj</code>.
4145  *
4146  * @param {!F.Behavior|!Node} domObj
4147  * @returns {!F.Behavior}
4148  */
4149 F.extractValueB = function (domObj) {
4150   if (domObj instanceof F.Behavior) {
4151     return domObj.liftB(function (dom) { return F.dom_.extractValueStaticB(dom); })
4152                  .switchB();
4153   } else {
4154     return F.dom_.extractValueStaticB(domObj);
4155   }
4156 };
4157 
4158 /**
4159  * @param {!F.Behavior|!Node} domObj
4160  * @returns {!F.Behavior}
4161  */
4162 F.$B = F.extractValueB;
4163 
4164 
4165 //into[index] = deepValueNow(from) via descending from object and mutating each field
4166 F.dom_.deepStaticUpdate = function (into, from, index) {
4167   var fV = (from instanceof F.Behavior)? from.valueNow() : from;
4168   if (typeof(fV) === 'object') {
4169     for (var i in fV) {
4170       if (!(Object.prototype) || !(Object.prototype[i])) {
4171         F.dom_.deepStaticUpdate(index? into[index] : into, fV[i], i);
4172       }
4173     }
4174   } else {
4175     var old = into[index];
4176     into[index] = fV;
4177   }
4178 };
4179 
4180 //note: no object may be time varying, just the fields
4181 //into[index] = from
4182 //only updates on changes
4183 F.dom_.deepDynamicUpdate = function (into, from, index) {
4184   var fV = (from instanceof F.Behavior)? from.valueNow() : from;
4185   if (typeof(fV) === 'object') {
4186     if (from instanceof F.Behavior) {
4187       throw 'deepDynamicUpdate: dynamic collections not supported';
4188     }
4189     for (var i in fV) {
4190       if (!(Object.prototype) || !(Object.prototype[i])) {
4191         F.dom_.deepDynamicUpdate(index? into[index] : into, fV[i], i);
4192       }
4193     }
4194   } else {
4195     if (from instanceof F.Behavior) {
4196       new F.EventStream(
4197         [from.changes()],
4198         function (p) {
4199           if (index) { 
4200             var old = into[index];
4201             into[index] = p.value;
4202           }
4203           else { into = p.value; } //TODO notify topE?
4204           return F.doNotPropagate;
4205         });
4206     }
4207   }
4208 };
4209 
4210 
4211 F.insertValue = function (val, domObj /* . indices */) {
4212   var indices = Array.prototype.slice.call(arguments, 2);
4213   var parent = F.dom_.getMostDom(domObj, indices);
4214   F.dom_.deepStaticUpdate(parent, val, 
4215       indices ? indices[indices.length - 1] : undefined);      
4216 };
4217 
4218 //TODO convenience method (default to firstChild nodeValue) 
4219 F.insertValueE = function (triggerE, domObj /* . indices */) {
4220   if (!(triggerE instanceof F.EventStream)) { throw 'insertValueE: expected Event as first arg'; } //SAFETY
4221   
4222   var indices = Array.prototype.slice.call(arguments, 2);
4223   var parent = F.dom_.getMostDom(domObj, indices);
4224   
4225     triggerE.mapE(function (v) {
4226       F.dom_.deepStaticUpdate(parent, v, indices? indices[indices.length - 1] : undefined);
4227     });
4228 };
4229 
4230 //insertValueB: F.Behavior * domeNode . Array (id) -> void
4231 //TODO notify adapter of initial state change?
4232 /**
4233  * Inserts each event in <i>triggerB</i> into the field <i>field</i> of the 
4234  * elmeent <i>dest</i></p>.
4235  *
4236  * @param {F.Behavior} triggerB
4237  * @param {Node} domObj
4238  * @param {...string} var_args
4239  */
4240 F.insertValueB = function (triggerB, domObj, var_args) { 
4241   
4242   var indices = Array.prototype.slice.call(arguments, 2);
4243   var parent = F.dom_.getMostDom(domObj, indices);
4244   
4245   
4246   //NOW
4247   F.dom_.deepStaticUpdate(parent, triggerB, indices ? indices[indices.length - 1] : undefined);
4248   
4249   //LATER
4250   F.dom_.deepDynamicUpdate(parent, triggerB, indices? indices[indices.length -1] : undefined);
4251   
4252 };
4253 
4254 //TODO copy dom event call backs of original to new? i don't thinks so
4255 //  complication though: registration of call backs should be scoped
4256 F.insertDomE = function (triggerE, domObj) {
4257   
4258   if (!(triggerE instanceof F.EventStream)) { throw 'insertDomE: expected Event as first arg'; } //SAFETY
4259   
4260   var objD = F.dom_.getObj(domObj);
4261   
4262   var res = triggerE.mapE(
4263     function (newObj) {
4264       //TODO safer check
4265       if (!((typeof(newObj) === 'object') && (newObj.nodeType === 1))) { 
4266         newObj = SPAN({}, newObj);
4267       }
4268       F.dom_.swapDom(objD, newObj);
4269       objD = newObj;
4270       return newObj; // newObj;
4271     });
4272   
4273   return res;
4274 };
4275 
4276 //insertDom: dom 
4277 //          * dom 
4278 //          [* (null | undefined | 'over' | 'before' | 'after' | 'leftMost' | 'rightMost' | 'beginning' | 'end']
4279 //          -> void
4280 // TODO: for consistency, switch replaceWithD, hookD argument order
4281 F.dom_.insertDomInternal = function (hookD, replaceWithD, optPosition) {
4282   switch (optPosition)
4283   {
4284   case undefined:
4285   case null:
4286   case 'over':
4287     F.dom_.swapDom(hookD,replaceWithD);
4288     break;
4289   case 'before':  
4290     hookD.parentNode.insertBefore(replaceWithD, hookD);
4291     break;
4292   case 'after':
4293     if (hookD.nextSibling) {
4294       hookD.parentNode.insertBefore(replaceWithD, hookD.nextSibling);
4295     } else {
4296       hookD.parentNode.appendChild(replaceWithD);
4297     }
4298     break;
4299   case 'leftMost':
4300     if (hookD.parentNode.firstChild) { 
4301       hookD.parentNode.insertBefore(
4302         replaceWithD, 
4303         hookD.parentNode.firstChild);
4304               } else { hookD.parentNode.appendChild(replaceWithD); }
4305               break;
4306             case 'rightMost':
4307               hookD.parentNode.appendChild(replaceWithD);
4308               break;
4309             case 'beginning':
4310               if (hookD.firstChild) { 
4311                 hookD.insertBefore(
4312                   replaceWithD, 
4313                   hookD.firstChild);
4314               } else { hookD.appendChild(replaceWithD); }
4315               break;
4316             case 'end':
4317               hookD.appendChild(replaceWithD);
4318               break;
4319             default:
4320               throw ('domInsert: unknown position: ' + optPosition);
4321   }
4322 };
4323 
4324 //insertDom: dom 
4325 //          * dom U String domID 
4326 //          [* (null | undefined | 'over' | 'before' | 'after' | 'leftMost' | 'rightMost' | 'beginning' | 'end']
4327 //          -> void
4328 F.insertDom = function (replaceWithD, hook, optPosition) {
4329   //TODO span of textnode instead of textnode?
4330   F.dom_.insertDomInternal(
4331     F.dom_.getObj(hook), 
4332     ((typeof(replaceWithD) === 'object') && (replaceWithD.nodeType > 0)) ? replaceWithD :
4333     document.createTextNode(replaceWithD),      
4334     optPosition);           
4335 };
4336 
4337 /**
4338  * if optID not specified, id must be set in init val of trigger
4339  * if position is not specified, default to 'over'
4340  *
4341  * @param {F.Behavior|Node} initTriggerB
4342  * @param {string=} optID
4343  * @param {string=} optPosition
4344  */
4345 F.insertDomB = function (initTriggerB, optID, optPosition) {
4346   
4347   if (!(initTriggerB instanceof F.Behavior)) { 
4348     initTriggerB = F.constantB(initTriggerB);
4349   }
4350   
4351   var triggerB = initTriggerB.liftB(function (d) { 
4352       if ((typeof(d) === 'object') && (d.nodeType >  0)) {
4353         return d;
4354       } else {
4355         var res = document.createElement('span'); //TODO createText instead
4356         res.appendChild(document.createTextNode(d));
4357         return res;
4358       }
4359     });
4360   
4361   var initD = triggerB.valueNow();
4362   if (!((typeof(initD) === 'object') && (initD.nodeType === 1))) { throw ('insertDomB: initial value conversion failed: ' + initD); } //SAFETY  
4363   
4364   F.dom_.insertDomInternal(
4365     optID === null || optID === undefined ? F.dom_.getObj(initD.getAttribute('id')) : F.dom_.getObj(optID), 
4366     initD, 
4367     optPosition);
4368   
4369   var resB = F.insertDomE(triggerB.changes(), initD).startsWith(initD);
4370   
4371   return resB;
4372 };
4373 
4374 /**
4375  * @param {Node} elem
4376  * @returns {F.EventStream}
4377  */
4378 F.mouseE = function(elem) {
4379   return F.extractEventE(elem,'mousemove')
4380   .mapE(function(evt) {
4381       if (evt.pageX | evt.pageY) {
4382         return { left: evt.pageX, top: evt.pageY };
4383       }
4384       else if (evt.clientX || evt.clientY) {
4385         return { left : evt.clientX + document.body.scrollLeft,
4386                  top: evt.clientY + document.body.scrollTop };
4387       }
4388       else {
4389         return { left: 0, top: 0 };
4390       }
4391   });
4392 };
4393 
4394 /**
4395  * Triggered when the mouse moves, carrying the mouse coordinates.
4396  *
4397  * @param {Node} elem
4398  * @returns {F.Behavior} <code>{ left: number, top: number }</code>
4399  */
4400 F.mouseB = function(elem) {
4401   return F.mouseE(elem).startsWith({ left: 0, top: 0 });
4402 };
4403 
4404 /**
4405  * @param {Node} elem
4406  * @returns {F.EventStream}
4407  */
4408 F.clicksE = function(elem) {
4409   return F.extractEventE(elem,'click');
4410 };
4411 
4412 
4413 //////////////////////////////////////////////////////////////////////////////
4414 // Combinators for web services
4415 
4416 F.xhr_.ajaxRequest = function(method,url,body,async,callback) {
4417   var xhr = new window.XMLHttpRequest();
4418   xhr.onload = function() { callback(xhr); };
4419   xhr.open(method,url,async);
4420   if (method === 'POST') {
4421     xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
4422   }
4423   xhr.send(body);
4424   return xhr;
4425 };
4426 
4427 F.xhr_.encodeREST = function(obj) {
4428   var str = "";
4429   for (var field in obj) {
4430     if (typeof(obj[field]) !== 'function') { // skips functions in the object
4431       if (str != '') { str += '&'; }
4432       str += field + '=' + encodeURIComponent(obj[field]);
4433     }
4434   }
4435   return str;
4436 };
4437 
4438 /**
4439  * Must be an event stream of bodies
4440  * 
4441  * @private
4442  * @param {!string} method PUT or POST
4443  * @param {!string} url URL to POST to
4444  * @returns {F.EventStream} an event stream carrying objects with three
4445  * fields: the request, the response, and the xhr object.
4446  */
4447 F.EventStream.prototype.xhrWithBody_ = function(method, url) {
4448   var respE = F.receiverE();
4449   this.mapE(function(body) {
4450     var xhr = new window.XMLHttpRequest();
4451     function callback() {
4452       if (xhr.readyState !== 4) {
4453         return;
4454       }
4455       respE.sendEvent({ request: body, response: xhr.responseText, xhr: xhr });
4456     }
4457     xhr.onload = callback;
4458     // We only do async. Build your own for synchronous.
4459     xhr.open(method, url, true);
4460     xhr.send(body);
4461   });
4462   return respE; 
4463 };
4464 
4465 /**
4466  * POST the body to url. The resulting event stream carries objects with three
4467  * fields: <code>{request: string, response: string, xhr: XMLHttpRequest}</code>
4468  *
4469  * @param {!string} url
4470  * @returns {F.EventStream}
4471  */
4472 F.EventStream.prototype.POST = function(url) {
4473   return this.xhrWithBody_('POST', url);
4474 };
4475 
4476 /**
4477  * Transforms a  stream of objects, <code>obj</code>, to a stream of fields
4478  * <code>obj[name]</code>.
4479  *
4480  * @param {!string} name
4481  * @returns {F.EventStream}
4482  */
4483 F.EventStream.prototype.index = function(name) {
4484   return this.mapE(function(obj) {
4485     if (typeof obj !== 'object' && obj !== null) {
4486       throw 'expected object';
4487     }
4488     return obj[name];
4489   });
4490 };
4491 
4492 /**
4493  * Parses a steram of JSON-serialized strings.
4494  *
4495  * @returns {F.EventStream}
4496  */
4497 F.EventStream.prototype.JSONParse = function() {
4498   return this.mapE(function(val) {
4499     return JSON.parse(val);
4500   });
4501 };
4502 
4503 /**
4504  * Serializes a stream of values.
4505  *
4506  * @returns {F.EventStream}
4507  */
4508 F.EventStream.prototype.JSONStringify = function() {
4509   return this.mapE(function(val) {
4510     return JSON.stringify(val);
4511   });
4512 };
4513 
4514 /**
4515  * @param {F.EventStream} requestE
4516  * @returns {F.EventStream}
4517  */
4518 F.getWebServiceObjectE = function(requestE) {
4519   var responseE = F.receiverE();
4520 
4521   requestE.mapE(function (obj) {
4522       var body = '';
4523       var method = 'GET';
4524       var url = obj.url;
4525       
4526       var reqType = obj.request ? obj.request : (obj.fields ? 'post' : 'get');
4527       if (obj.request === 'get') {
4528         if (obj.fields) { url += "?" + F.xhr_.encodeREST(obj.fields); }
4529         body = '';
4530         method = 'GET';
4531       } else if (obj.request === 'post') {
4532         body = JSON.stringify(obj.fields); 
4533         method = 'POST';
4534       } else if (obj.request === 'rawPost') {
4535         body = obj.body;
4536         method = 'POST';
4537       }
4538       else if (obj.request === 'rest') {
4539         body = F.xhr_.encodeREST(obj.fields);
4540         method = 'POST';
4541       }
4542       else {
4543         throw("Invalid request type: " + obj.request);
4544       }
4545       
4546       var async = obj.async !== false;
4547       
4548       var xhr;
4549       
4550       // Branch on the response type to determine how to parse it
4551       if (obj.response === 'json') {
4552         xhr = F.xhr_.ajaxRequest(method,url,body,async,
4553           function(xhr) {
4554             responseE.sendEvent(JSON.parse(xhr.responseText)); 
4555           });
4556       }
4557       else if (obj.response === 'xml') {
4558         F.xhr_.ajaxRequest(method,url,body,async,
4559           function(xhr) {
4560             responseE.sendEvent(xhr.responseXML);
4561           });
4562       }
4563       else if (obj.response === 'plain' || !obj.response) {
4564         F.xhr_.ajaxRequest(method,url,body,async,
4565           function(xhr) {
4566             responseE.sendEvent(xhr.responseText);
4567         });
4568       }
4569       else {
4570         throw('Unknown response format: ' + obj.response);
4571       }
4572     return F.doNotPropagate;
4573   });
4574   
4575   return responseE;
4576 };
4577 function AuroraDom(){
4578     this.get = function(id){
4579         if(typeof id == 'string'){
4580             return document.getElementById(id);
4581         }
4582         return id;
4583     }                           
4584     this.createDiv = function(id, innerHTML, className){//TODO: refactor this to go id, className, innerHTML
4585         log("CREATE DIVV");
4586         return this.create('div', id, className, innerHTML);
4587     }
4588     this.createSpan = function(id, innerHTML, className){//TODO: refactor this to go id, className, innerHTML
4589         return this.create('span', id, className, innerHTML);
4590     }
4591     this.create = function(type, id, className, innerHTML){//TODO: refactor this to go id, className, innerHTML
4592         var element = document.createElement(type);
4593         if(id!=undefined){
4594             element.id = id;
4595         }
4596         if(className!=undefined){
4597             element.className = className;
4598         }
4599         if(innerHTML!=undefined){
4600             element.innerHTML = innerHTML;
4601         } 
4602         return element;
4603     }
4604     this.createOption = function(id, className, innerText, value){
4605         var element = this.create('option', undefined, undefined, innerText);
4606         element.value = value;
4607         element.innerText = innerText; 
4608         element.text = innerText;
4609         return element;
4610     }
4611     this.createImg = function(id, className, src){
4612         var element = document.createElement('img');
4613         if(id!=undefined){
4614             element.id = id;
4615         }
4616         if(className!=undefined){
4617             element.className = className;
4618         }
4619         if(src!=undefined){
4620             element.src = src;
4621         }
4622         return element;
4623     }
4624     this.stopEvent = function(event){
4625         event.stopPropagation();  
4626         event.preventDefault();
4627     }
4628     this.getElementsByClassName = function(class_name, tag, elm) {
4629         var docList = elm.getElementsByTagName('*');
4630         var matchArray = [];
4631         /*Create a regular expression object for class*/
4632         var re = new RegExp("(?:^|\\s)"+class_name+"(?:\\s|$)");
4633         for (var i = 0; i < docList.length; i++) {
4634             if (re.test(docList[i].className) ) {
4635                 matchArray.push(docList[i]);
4636             }                                                  
4637         }
4638         return matchArray;
4639     }
4640 }
4641 
4642 function parseMysqlDate(mysql_string){ 
4643    if(typeof mysql_string === 'string')
4644    {
4645       var t = mysql_string.split(/[- :]/);
4646       return new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);          
4647    }
4648    return null;   
4649 }
4650 function createButton(value, className){
4651     var button = createDomElement("input", undefined,"button");
4652     button.type = "submit";
4653     button.value = value;
4654     if(className!=undefined)
4655         button.className = className;
4656     return button;
4657 }
4658 String.prototype['contains'] = function(str){
4659     return (this.indexOf(str) >= 0);
4660 }
4661 //window.getElementsByClassName = DOM.getElementsByClassName;
4662 if(typeof(Element)!='undefined'){
4663     Element.prototype.removeChildren = function(element){
4664         if(element==undefined)
4665             element = this;
4666         while (element.hasChildNodes()) {
4667             element.removeChild(element.lastChild);
4668         }
4669     }
4670 }
4671 function getMilliseconds(){
4672 var d = new Date();
4673 return d.getTime(); 
4674 } 
4675 function createDomElement(type, id, className, innerHTML){
4676     var ele = document.createElement(type);
4677     if(id!=undefined&&id.length>0)
4678     ele.id = id;
4679     if(className!=undefined&&className.length>0)
4680     ele.className = className; 
4681     if(innerHTML!=undefined&&innerHTML.length>0)
4682     ele.innerHTML = innerHTML;
4683     return ele; 
4684 }
4685 function createIcon(src){
4686     var saveButton = document.createElement("img");
4687     saveButton.src=src;
4688     saveButton.style.cursor="pointer";
4689     return saveButton;
4690 }
4691 function findParentNodeWithTag(element, tag){
4692     if(element==undefined||element==null)
4693         return undefined; 
4694     else if(element.tagName.toUpperCase() == tag.toUpperCase())
4695         return element;
4696     return findParentNodeWithTag(element.parentNode, tag);    
4697 }
4698 function findTableRowIndex(table, row){
4699     for(i=0; i<table.rows.length; i++){
4700         if(table.rows[i]==row)
4701             return i;
4702     }
4703     return -1;
4704 }
4705 
4706 function stopEventBubble(event){
4707     agent = jQuery.browser;
4708     if(agent.msie) {
4709         event.cancelBubble = true;
4710     } else {
4711         event.stopPropagation();
4712     }
4713 }
4714 function ajax(options) {
4715     if(typeof jQuery != 'undefined'){
4716         jQuery.ajax(options);
4717     }
4718     else{
4719         var type = (options["type"]=='undefined')?"POST":options["type"];
4720         var success = options["success"];
4721         var error = options["fail"];
4722         var dataType = options["dataType"];
4723         var url = options["url"];
4724         var data = options["data"];
4725         
4726         function getXMLHttpRequest() {
4727             if (window.XMLHttpRequest) {
4728                 return new window.XMLHttpRequest;
4729             } else {
4730                 try {
4731                     return new ActiveXObject("MSXML2.XMLHTTP");
4732                 } catch (ex) {
4733                     return null;
4734                 }
4735             }
4736         }
4737 
4738         if(typeof data == 'string'){
4739             data = JSON.parse(data);
4740         } 
4741         var dataStr="";
4742         var count =0;
4743         for(index in data){
4744             var dataPiece = (typeof(data[index])=='string')?data[index]:JSON.stringify(data[index]);
4745             if(count!=0)
4746                 dataStr+="&";
4747             dataStr += index+"="+dataPiece;
4748             count++;
4749         }
4750         //dataStr = dataStr.replaceAll("\"", "'");
4751         /*var oReq = getXMLHttpRequest();
4752         if (oReq != null) {
4753             oReq.open("POST", url, true);
4754             oReq.onreadystatechange = handler;
4755             oReq.send(dataStr);
4756         } else {
4757             UI.showMessage("AJAX (XMLHTTP) not supported.");
4758         }  */
4759         var xmlhttp = getXMLHttpRequest(); 
4760         
4761         if (xmlhttp != null) {
4762             xmlhttp.open("POST",url,true);
4763             xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
4764             xmlhttp.send(dataStr);
4765             xmlhttp.onreadystatechange = function(){
4766                 if (xmlhttp.readyState == 4 /* complete */ ) {
4767                     if (xmlhttp.status == 200 && success!=undefined) {
4768                         success(xmlhttp.responseText);
4769                     }
4770                     else if(error!=undefined)
4771                         error(xmlhttp.status);
4772                 }
4773             };
4774         } else {
4775             UI.showMessage("AJAX (XMLHTTP) not supported.");
4776         }
4777     }    
4778 }
4779 window['createBehaviour'] = function(initialValue){
4780     return F.receiverE().startsWith(initialValue);
4781 }
4782 function getPos(el) {
4783     // yay readability
4784     for (var lx=0, ly=0;el != null;lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent){}
4785     return {x: lx,y: ly};
4786 }
4787 
4788 function aurora_viewport()
4789 {
4790 var e = window
4791 , a = 'inner';
4792 if ( !( 'innerWidth' in window ) )
4793 {
4794 a = 'client';
4795 e = document.documentElement || document.body;
4796 }
4797 return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
4798 }
4799 //John Resig   
4800 var ready = ( function () {
4801 function addEvent( obj, type, fn ) {
4802     if (obj.addEventListener) {
4803         obj.addEventListener( type, fn, false );
4804         EventCache.add(obj, type, fn);
4805     }
4806     else if (obj.attachEvent) {
4807         obj["e"+type+fn] = fn;
4808         obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
4809         obj.attachEvent( "on"+type, obj[type+fn] );
4810         EventCache.add(obj, type, fn);
4811     }
4812     else {
4813         obj["on"+type] = obj["e"+type+fn];
4814     }
4815 }
4816 var EventCache = function(){
4817     var listEvents = [];
4818     return {
4819         listEvents : listEvents,
4820         add : function(node, sEventName, fHandler){
4821             listEvents.push(arguments);
4822         },
4823         flush : function(){
4824             var i, item;
4825             for(i = listEvents.length - 1; i >= 0; i = i - 1){
4826                 item = listEvents[i];
4827                 if(item[0].removeEventListener){
4828                     item[0].removeEventListener(item[1], item[2], item[3]);
4829                 };
4830                 if(item[1].substring(0, 2) != "on"){
4831                     item[1] = "on" + item[1];
4832                 };
4833                 if(item[0].detachEvent){
4834                     item[0].detachEvent(item[1], item[2]);
4835                 };
4836                 item[0][item[1]] = null;
4837             };
4838         }
4839     };
4840 }();
4841 // Usage
4842 /*addEvent(window,'unload',EventCache.flush);
4843 addEvent(window,'load', function(){});       */
4844 
4845   function ready( f ) {
4846     if( ready.done ) return f();
4847 
4848     if( ready.timer ) {
4849       ready.ready.push(f);
4850     } else {
4851       addEvent( window, "load", isDOMReady );
4852       ready.ready = [ f ];
4853       ready.timer = setInterval(isDOMReady, 13);
4854     }
4855   };
4856 
4857   function isDOMReady() {
4858     if( ready.done ) return false;
4859 
4860     if( document && document.getElementsByTagName && document.getElementById && document.body ) {
4861       clearInterval( ready.timer );
4862       ready.timer = null;
4863       for( var i = 0; i < ready.ready.length; i++ ) {
4864         ready.ready[i]();
4865       }
4866       ready.ready = null;
4867       ready.done = true;
4868     }
4869   }
4870 
4871   return ready;
4872 })();
4873 
4874 
4875 function caller(ob, depth, maxDepth){
4876     if(depth==undefined)
4877         depth = 1;
4878     if(maxDepth==undefined)
4879         maxDepth = 10;
4880     log("Probing at depth: "+depth);
4881     log(ob);
4882     log(ob.callee);
4883     log(ob.callee.toString);
4884     log(ob.callee.caller);
4885     log(ob.callee.caller.toString());
4886     log("");
4887     if(depth<=maxDepth)
4888         caller(ob.callee.caller.arguments, depth+1, maxDepth);
4889 }
4890 function auroraParseBoolean(b){
4891     if(b=="true"||b==true)
4892         return true;
4893     return false;
4894 }
4895 
4896 function getViewPortDimensions(){
4897  
4898  var viewportwidth;
4899  var viewportheight;
4900   
4901  // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
4902   
4903  if (typeof window.innerWidth != 'undefined')
4904  {
4905       viewportwidth = window.innerWidth,
4906       viewportheight = window.innerHeight
4907  }
4908   
4909 // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
4910  
4911  else if (typeof document.documentElement != 'undefined'
4912      && typeof document.documentElement.clientWidth !=
4913      'undefined' && document.documentElement.clientWidth != 0)
4914  {
4915        viewportwidth = document.documentElement.clientWidth,
4916        viewportheight = document.documentElement.clientHeight
4917  }
4918   
4919  // older versions of IE
4920   
4921  else
4922  {
4923        viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
4924        viewportheight = document.getElementsByTagName('body')[0].clientHeight
4925  }
4926 return {width: viewportwidth, height: viewportheight};
4927 }
4928 // Array Remove - By John Resig (MIT Licensed)
4929 
4930 /*Array.prototype.remove = function(from, to) {
4931   var rest = this.slice((to || from) + 1 || this.length);
4932   this.length = from < 0 ? this.length + from : from;
4933   return this.push.apply(this, rest);
4934 };      */
4935 
4936 
4937 Array.indexOf = function(array, needle) {
4938         return arrayIndexOf(array, needle);
4939     };  
4940 
4941 arrayIndexOf = function(arr, needle) {
4942         for(var i = 0; i < arr.length; i++) {
4943             if(arr[i] === needle) {
4944                 return i;
4945             }
4946         }
4947         return -1;
4948     };            
4949 function arrayCut(array, index) {
4950     array.splice(index,1); 
4951 };
4952 Array.max = function( array ){
4953     return Math.max.apply( Math, array );
4954 };
4955 
4956 Array.min = function( array ){
4957     return Math.min.apply( Math, array );
4958 };
4959 //}
4960 /*Array.prototype.contains = function(ob){
4961     return this.indexOf('Sam') > -1;
4962 }    */
4963 function arrayContains(array, search){
4964     return arrayIndexOf(array, search) > -1; 
4965 }
4966 
4967 String.prototype.startsWith = function(prefix) {
4968     return this.indexOf(prefix) === 0;
4969 };
4970 
4971 String.prototype.endsWith = function(suffix) {
4972     return this.match(suffix+"$") == suffix;
4973 };
4974 if(!String.prototype.trim) {
4975   String.prototype.trim = function () {
4976     return this.replace(/^\s+|\s+$/g,'');
4977   };
4978 }
4979 
4980 String.prototype.replaceAll = function(replace, with_this) {
4981   return this.replace(new RegExp(replace, 'g'),with_this);
4982 };
4983 /*if (!document.addEventListener && document.attachEvent)
4984 {
4985     Object.prototype.addEventListener = function(eventName, func, capture)
4986     {
4987         if (this.attachEvent)
4988             this.attachEvent('on' + eventName, func);
4989     }
4990 
4991     var i, l = document.all.length;
4992 
4993     for (i = 0; i < l; i++)
4994         document.all[i].addEventListener = Object.prototype.addEventListener;
4995 
4996     window.addEventListener = Object.prototype.addEventListener;
4997     document.addEventListener = Object.prototype.addEventListener;
4998 }*/
4999 if(!window.addEventListener && document.attachEvent){
5000 window.addEventListener = function(eventName, func, capture){
5001         this.attachEvent('on' + eventName, func);
5002     }
5003 }
5004 
5005 
5006 /*document.getElementsByClassName = function(cl) {
5007 var retnode = [];
5008 var myclass = new RegExp('\\b'+cl+'\\b');
5009 var elem = this.getElementsByTagName('*');
5010 for (var i = 0; i < elem.length; i++) {
5011 var classes = elem[i].className;
5012 if (myclass.test(classes)) retnode.push(elem[i]);
5013 }
5014 return retnode;
5015 }; 
5016 function getElementsByClassName2(className, body){
5017     var retnode = [];
5018      var element = document.createElement('div');
5019     element.innerHTML = body;
5020     var tags = element.getElementsByTagName('img');
5021     for(index in tags){
5022         var tag = tags[index];
5023         if(tag.className==className){
5024             retnode.push(tag);
5025         }
5026     }
5027     return retnode;
5028 }          */
5029 function test(ob){
5030     alert(getClassName(ob)+" | "+ob+" | "+ObjectToString(ob));
5031 }
5032 function getClassName(element) { 
5033    var funcNameRegex = /function (.{1,})\(/;
5034    var results = (funcNameRegex).exec((element).constructor.toString());
5035    return (results && results.length > 1) ? results[1] : "";
5036 }; 
5037 
5038 function loadXMLString(txt)
5039 {
5040 if (window.DOMParser)
5041   {
5042   parser=new DOMParser();
5043   xmlDoc=parser.parseFromString(txt,"text/xml");
5044   }
5045 else // Internet Explorer
5046   {
5047   xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
5048   xmlDoc.async="false";
5049   xmlDoc.loadXML(txt);
5050   }
5051 return xmlDoc;
5052 }
5053 /*document.getElementsByClassName = function(class_name) {
5054     return getElementsByClassName(class_name, '', null); 
5055 }*/
5056 getElementsByClassName = function(class_name, tag, elm) {
5057     doc = elm || this;
5058     var docList = doc.all || doc.getElementsByTagName('*');
5059     var matchArray = new Array();
5060 
5061     /*Create a regular expression object for class*/
5062     var re = new RegExp("(?:^|\\s)"+class_name+"(?:\\s|$)");
5063     for (var i = 0; i < docList.length; i++) {
5064         //showObj(docList[i]);
5065         if (re.test(docList[i].className) ) {
5066             matchArray[matchArray.length] = docList[i];
5067         }
5068     }
5069     return matchArray;
5070 }
5071 
5072 /*var getElementsByClassName = function (className, tag, elm){
5073     if (document.getElementsByClassName) {
5074         getElementsByClassName = function (className, tag, elm) {
5075             elm = elm || document;
5076             var elements = elm.getElementsByClassName(className),
5077                 nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
5078                 returnElements = [],
5079                 current;
5080             for(var i=0, il=elements.length; i<il; i+=1){
5081                 current = elements[i];
5082                 if(!nodeName || nodeName.test(current.nodeName)) {
5083                     returnElements.push(current);
5084                 }
5085             }
5086             return returnElements;
5087         }; 
5088     }
5089     else if (document.evaluate) {
5090         getElementsByClassName = function (className, tag, elm) {
5091             tag = tag || "*";
5092             elm = elm || document;
5093             var classes = className.split(" "),
5094                 classesToCheck = "",
5095                 xhtmlNamespace = "http://www.w3.org/1999/xhtml",
5096                 namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
5097                 returnElements = [],
5098                 elements,
5099                 node;
5100             for(var j=0, jl=classes.length; j<jl; j+=1){
5101                 classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
5102             }
5103             try    {
5104                 elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
5105             }
5106             catch (e) {
5107                 elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
5108             }
5109             while ((node = elements.iterateNext())) {
5110                 returnElements.push(node);
5111             }
5112             return returnElements;
5113         };
5114     }
5115     else {
5116         getElementsByClassName = function (className, tag, elm) {
5117             tag = tag || "*";
5118             elm = elm || document;
5119             var classes = className.split(" "),
5120                 classesToCheck = [],
5121                 elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
5122                 current,
5123                 returnElements = [],
5124                 match;
5125             for(var k=0, kl=classes.length; k<kl; k+=1){
5126                 classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
5127             }
5128             for(var l=0, ll=elements.length; l<ll; l+=1){
5129                 current = elements[l];
5130                 match = false;
5131                 for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
5132                     match = classesToCheck[m].test(current.className);
5133                     if (!match) {
5134                         break;
5135                     }
5136                 }
5137                 if (match) {
5138                     returnElements.push(current);
5139                 }
5140             }
5141             return returnElements;
5142         };
5143     }
5144     return getElementsByClassName(className, tag, elm);
5145 };
5146         */ 
5147 function createDomElement(type, id, className, innerHTML){
5148     var ele = document.createElement(type);
5149     if(id.length>0)
5150     ele.id = id;
5151     if(className.length>0)
5152     ele.className = className; 
5153     if(innerHTML.length>0)
5154     ele.innerHTML = innerHTML;
5155     return ele; 
5156 }
5157 function getElement(id){
5158     return document.getElementById(id);
5159 }
5160 function disableEventPropagation(event)
5161 {
5162    if (event.stopPropagation){
5163        event.stopPropagation();
5164    }
5165    else if(window.event){
5166       window.event.cancelBubble=true;
5167    }
5168 } 
5169 function disableHighlight(target){
5170 	target = (typeof(target)=='string')?DOM.get(target):target;
5171     if(document.all)
5172         target.onselectstart = handleSelectAttempt;
5173     target.onmousedown = handleSelectAttempt;   
5174 }
5175 
5176 function handleSelectAttempt(e) {
5177     var sender = e && e.target || window.event.srcElement;
5178     if (window.event) {
5179         event.returnValue = true;
5180     }
5181     return true;
5182 }
5183 function makeUnselectable(node) {
5184     if (node.nodeType == 1) {
5185         node.unselectable = true;
5186     }
5187     var child = node.firstChild;
5188     while (child) {
5189         makeUnselectable(child);
5190         child = child.nextSibling;
5191     }
5192 }
5193 
5194 function objectEquals(ob1, ob2)
5195 {
5196     if(typeof(ob1)=='undefined'||typeof(ob2)=='undefined'){
5197         return (typeof(ob1)=='undefined'&&typeof(ob2)=='undefined');
5198     }
5199 
5200 
5201   var p;
5202   for(p in ob1) {
5203       if(typeof(ob2)=='undefined'||typeof(ob2[p])=='undefined') {return false;}
5204   }
5205 
5206   for(p in ob1) {
5207       if (ob1[p]) {
5208           switch(typeof(ob1[p])) {
5209               case 'object':
5210                   if (!objectEquals(ob1[p], ob2[p])) { return false; } break;
5211               case 'function':
5212                   if (typeof(ob2)=='undefined' || typeof(ob2[p])=='undefined' ||
5213                       (p != 'equals' && ob1[p].toString() != ob2[p].toString()))
5214                       return false;
5215                   break;
5216               default:
5217                   if (ob1[p] != ob2[p]) { return false; }
5218           }
5219       } else {
5220           if (ob2[p])
5221               return false;
5222       }
5223   }
5224 
5225   for(p in ob2) {
5226       if(typeof(ob1)=='undefined'||typeof(ob1[p])=='undefined') {return false;}
5227   }
5228 
5229   return true;
5230 }   
5231 //Object.prototype.equals = objectEquals;
5232 function clone(source){
5233     return cloneObject(source);
5234 }  
5235 //Object.prototype.clone = clone;
5236 function cloneObject(source) {
5237    if (source instanceof Array) {
5238         var copy = [];
5239         for (var i = 0; i < source.length; i++) {
5240             copy[i] = cloneObject(source[i]);
5241         }
5242         return copy;
5243     }
5244    var copiedObject = {};
5245    jQuery.extend(true, copiedObject,source);
5246    return copiedObject;
5247    }
5248 
5249 
5250 /*  
5251 /*Object.extend = function(destination, source) {
5252   for (var property in source)
5253     destination[property] = source[property];
5254   return destination;
5255 };    */
5256 
5257 /*function cloneObject(source) {
5258     /*for (i in source) {
5259         if (typeof source[i] == 'source') {
5260             this[i] = new cloneObject(source[i]);
5261         }
5262         else{
5263             this[i] = source[i];
5264     }
5265     } 
5266 //    return Object.extend({ }, object);
5267    // return jQuery.extend(true, {}, source);
5268    //return clone(source);
5269    
5270    var copiedObject = {};
5271    jQuery.extend(copiedObject,source);
5272    return copiedObject;
5273 }  
5274 function clone(obj) {
5275     // Handle the 3 simple types, and null or undefined
5276     if (null == obj || "object" != typeof obj) return obj;
5277 
5278     // Handle Date
5279     if (obj instanceof Date) {
5280         var copy = new Date();
5281         copy.setTime(obj.getTime());
5282         return copy;
5283     }
5284 
5285     // Handle Array
5286     if (obj instanceof Array) {
5287         var copy = [];
5288         for (var i = 0, len = obj.length; i < len; ++i) {
5289             copy[i] = clone(obj[i]);
5290         }
5291         return copy;
5292     }
5293 
5294     // Handle Object
5295     if (obj instanceof Object) {
5296         var copy = {};
5297         for (var attr in obj) {
5298             if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
5299         }
5300         return copy;
5301     }
5302 
5303     throw new Error("Unable to copy obj! Its type isn't supported.");
5304 }
5305 
5306        */
5307        
5308        //LZW Compression/Decompression for Strings
5309 var LZW = {
5310     compress: function (uncompressed) {
5311         "use strict";
5312         // Build the dictionary.
5313         var i,
5314             dictionary = {},
5315             c,
5316             wc,
5317             w = "",
5318             result = [],
5319             dictSize = 256;
5320         for (i = 0; i < 256; i += 1) {
5321             dictionary[String.fromCharCode(i)] = i;
5322         }
5323  
5324         for (i = 0; i < uncompressed.length; i += 1) {
5325             c = uncompressed.charAt(i);
5326             wc = w + c;
5327             if (dictionary[wc]) {
5328                 w = wc;
5329             } else {
5330                 result.push(dictionary[w]);
5331                 // Add wc to the dictionary.
5332                 dictionary[wc] = dictSize++;
5333                 w = String(c);
5334             }
5335         }
5336  
5337         // Output the code for w.
5338         if (w !== "") {
5339             result.push(dictionary[w]);
5340         }
5341         return result;
5342     },
5343  
5344  
5345     decompress: function (compressed) {
5346         "use strict";
5347         // Build the dictionary.
5348         var i,
5349             dictionary = [],
5350             w,
5351             result,
5352             k,
5353             entry = "",
5354             dictSize = 256;
5355         for (i = 0; i < 256; i += 1) {
5356             dictionary[i] = String.fromCharCode(i);
5357         }
5358  
5359         w = String.fromCharCode(compressed[0]);
5360         result = w;
5361         for (i = 1; i < compressed.length; i += 1) {
5362             k = compressed[i];
5363             if (dictionary[k]) {
5364                 entry = dictionary[k];
5365             } else {
5366                 if (k === dictSize) {
5367                     entry = w + w.charAt(0);
5368                 } else {
5369                     return null;
5370                 }
5371             }
5372  
5373             result += entry;
5374  
5375             // Add w+entry[0] to the dictionary.
5376             dictionary[dictSize++] = w + entry.charAt(0);
5377  
5378             w = entry;
5379         }
5380         return result;
5381     }
5382 }; // For Test Purposes
5383 /*    comp = LZW.compress("TOBEORNOTTOBEORTOBEORNOT"),
5384     decomp = LZW.decompress(comp);
5385 document.write(comp + '<br>' + decomp);*/
5386 
5387 
5388 
5389 
5390 /**
5391 *
5392 *  MD5 (Message-Digest Algorithm)
5393 *  http://www.webtoolkit.info/
5394 *
5395 **/
5396  
5397 var MD5 = function (string) {
5398  
5399     function RotateLeft(lValue, iShiftBits) {
5400         return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
5401     }
5402  
5403     function AddUnsigned(lX,lY) {
5404         var lX4,lY4,lX8,lY8,lResult;
5405         lX8 = (lX & 0x80000000);
5406         lY8 = (lY & 0x80000000);
5407         lX4 = (lX & 0x40000000);
5408         lY4 = (lY & 0x40000000);
5409         lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
5410         if (lX4 & lY4) {
5411             return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
5412         }
5413         if (lX4 | lY4) {
5414             if (lResult & 0x40000000) {
5415                 return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
5416             } else {
5417                 return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
5418             }
5419         } else {
5420             return (lResult ^ lX8 ^ lY8);
5421         }
5422      }
5423  
5424      function F(x,y,z) { return (x & y) | ((~x) & z); }
5425      function G(x,y,z) { return (x & z) | (y & (~z)); }
5426      function H(x,y,z) { return (x ^ y ^ z); }
5427     function I(x,y,z) { return (y ^ (x | (~z))); }
5428  
5429     function FF(a,b,c,d,x,s,ac) {
5430         a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
5431         return AddUnsigned(RotateLeft(a, s), b);
5432     };
5433  
5434     function GG(a,b,c,d,x,s,ac) {
5435         a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
5436         return AddUnsigned(RotateLeft(a, s), b);
5437     };
5438  
5439     function HH(a,b,c,d,x,s,ac) {
5440         a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
5441         return AddUnsigned(RotateLeft(a, s), b);
5442     };
5443  
5444     function II(a,b,c,d,x,s,ac) {
5445         a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
5446         return AddUnsigned(RotateLeft(a, s), b);
5447     };
5448  
5449     function ConvertToWordArray(string) {
5450         var lWordCount;
5451         var lMessageLength = string.length;
5452         var lNumberOfWords_temp1=lMessageLength + 8;
5453         var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
5454         var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
5455         var lWordArray=Array(lNumberOfWords-1);
5456         var lBytePosition = 0;
5457         var lByteCount = 0;
5458         while ( lByteCount < lMessageLength ) {
5459             lWordCount = (lByteCount-(lByteCount % 4))/4;
5460             lBytePosition = (lByteCount % 4)*8;
5461             lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
5462             lByteCount++;
5463         }
5464         lWordCount = (lByteCount-(lByteCount % 4))/4;
5465         lBytePosition = (lByteCount % 4)*8;
5466         lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
5467         lWordArray[lNumberOfWords-2] = lMessageLength<<3;
5468         lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
5469         return lWordArray;
5470     };
5471  
5472     function WordToHex(lValue) {
5473         var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
5474         for (lCount = 0;lCount<=3;lCount++) {
5475             lByte = (lValue>>>(lCount*8)) & 255;
5476             WordToHexValue_temp = "0" + lByte.toString(16);
5477             WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
5478         }
5479         return WordToHexValue;
5480     };
5481  
5482     function Utf8Encode(string) {
5483         string = string.replace(/\r\n/g,"\n");
5484         var utftext = "";
5485  
5486         for (var n = 0; n < string.length; n++) {
5487  
5488             var c = string.charCodeAt(n);
5489  
5490             if (c < 128) {
5491                 utftext += String.fromCharCode(c);
5492             }
5493             else if((c > 127) && (c < 2048)) {
5494                 utftext += String.fromCharCode((c >> 6) | 192);
5495                 utftext += String.fromCharCode((c & 63) | 128);
5496             }
5497             else {
5498                 utftext += String.fromCharCode((c >> 12) | 224);
5499                 utftext += String.fromCharCode(((c >> 6) & 63) | 128);
5500                 utftext += String.fromCharCode((c & 63) | 128);
5501             }
5502  
5503         }
5504  
5505         return utftext;
5506     };
5507  
5508     var x=Array();
5509     var k,AA,BB,CC,DD,a,b,c,d;
5510     var S11=7, S12=12, S13=17, S14=22;
5511     var S21=5, S22=9 , S23=14, S24=20;
5512     var S31=4, S32=11, S33=16, S34=23;
5513     var S41=6, S42=10, S43=15, S44=21;
5514  
5515     string = Utf8Encode(string);
5516  
5517     x = ConvertToWordArray(string);
5518  
5519     a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
5520  
5521     for (k=0;k<x.length;k+=16) {
5522         AA=a; BB=b; CC=c; DD=d;
5523         a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
5524         d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
5525         c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
5526         b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
5527         a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
5528         d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
5529         c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
5530         b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
5531         a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
5532         d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
5533         c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
5534         b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
5535         a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
5536         d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
5537         c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
5538         b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
5539         a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
5540         d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
5541         c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
5542         b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
5543         a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
5544         d=GG(d,a,b,c,x[k+10],S22,0x2441453);
5545         c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
5546         b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
5547         a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
5548         d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
5549         c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
5550         b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
5551         a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
5552         d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
5553         c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
5554         b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
5555         a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
5556         d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
5557         c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
5558         b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
5559         a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
5560         d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
5561         c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
5562         b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
5563         a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
5564         d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
5565         c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
5566         b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
5567         a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
5568         d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
5569         c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
5570         b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
5571         a=II(a,b,c,d,x[k+0], S41,0xF4292244);
5572         d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
5573         c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
5574         b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
5575         a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
5576         d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
5577         c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
5578         b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
5579         a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
5580         d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
5581         c=II(c,d,a,b,x[k+6], S43,0xA3014314);
5582         b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
5583         a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
5584         d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
5585         c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
5586         b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
5587         a=AddUnsigned(a,AA);
5588         b=AddUnsigned(b,BB);
5589         c=AddUnsigned(c,CC);
5590         d=AddUnsigned(d,DD);
5591     }
5592  
5593     var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
5594  
5595     return temp.toLowerCase();
5596 }
5597 
5598 /*objectEquals = function(ob1, x)
5599 {
5600   for(p in ob1) {
5601       if(typeof(x[p])=='undefined') {return false;}
5602   }
5603 
5604   for(p in ob1) {
5605       if (ob1[p]) {
5606           switch(typeof(ob1[p])) {
5607               case 'object':
5608                   if (!objectEquals(ob1[p], x[p])) { return false; } break;
5609               case 'function':
5610                   if (typeof(x[p])=='undefined' ||
5611                       (p != 'equals' && ob1[p].toString() != x[p].toString()))
5612                       return false;
5613                   break;
5614               default:
5615                   if (ob1[p] != x[p]) { return false; }
5616           }
5617       } else {
5618           if (x[p])
5619               return false;
5620       }
5621   }
5622 
5623   for(p in x) {
5624       if(typeof(ob1[p])=='undefined') {return false;}
5625   }
5626 
5627   return true;
5628 } */
5629 
5630 
5631          
5632 function loadScriptE(url){
5633     var rec = F.receiverE();
5634     var script = document.createElement("script")
5635     script.type = "text/javascript";
5636 
5637     if (script.readyState){  //IE
5638         script.onreadystatechange = function(){
5639             if (script.readyState == "loaded" || script.readyState == "complete"){
5640                 script.onreadystatechange = null;
5641                 rec.sendEvent(true);
5642             }
5643         };
5644     } else {  //Others
5645         script.onload = function(){
5646             rec.sendEvent(true);
5647         };
5648     }
5649 
5650     script.src = url;
5651     document.getElementsByTagName("head")[0].appendChild(script);
5652     return rec;
5653 }
5654 
5655 function UrlExists(url)
5656 {
5657     var http = new XMLHttpRequest();
5658     http.open('HEAD', url, false);
5659     http.send();
5660     return http.status!=404;
5661 }
5662 
5663 function aurora_requestWidgetRefE(page){
5664     var rec = F.receiverE();
5665     jQuery.ajax({
5666         dataType: 'json',
5667         type: "post",
5668         data: {page: page},
5669         url: SETTINGS.scriptPath+"request/getWidgetRef",
5670         success: function(data){
5671             rec.sendEvent(data);
5672         },
5673         error: connectionError
5674     });
5675     return rec;
5676 }
5677 function aurora_requestWidgetRef(page, callback){
5678     jQuery.ajax({
5679         dataType: 'json',
5680         type: "post",
5681         data: {page: page},
5682         url: SETTINGS.scriptPath+"request/getWidgetRef",
5683         success: function(data){
5684             callback(data);
5685         },
5686         error: connectionError
5687     });
5688 }
5689 function getPlaceholderDimensions(placeholder){
5690     var width = placeholder.getAttribute('width');
5691     var height = placeholder.getAttribute('height');
5692     width = (width!=undefined)?width:placeholder.style.width;
5693     height = (height!=undefined)?height:placeholder.style.height;
5694     wUnit = width.contains("%")?"%":"px";
5695     hUnit = height.contains("%")?"%":"px";
5696     return {width: parseInt(width.replace('px', '')), height: parseInt(height.replace('px', '')), wUnit: wUnit, hUnit:hUnit};
5697 }
5698 
5699 function getObjectValues(ob){
5700     var ret = [];
5701     log("getObjectValues");
5702     for(index in ob){
5703     	log(index);
5704     	log(ob[index]);
5705         ret.push(ob[index]);
5706     }
5707     return ret;
5708 }     
5709 
5710 /**
5711  *  RemoteData
5712  * @constructor
5713  */
5714  
5715 
5716 function RemoteData(key, context, initialValue, pollRate){
5717    
5718 this.hash = "HASH";
5719     this.eventE = F.receiverE();
5720     this.event = this.eventE;
5721     this.originBehaviour = this.event.startsWith(initialValue);
5722     this.pollRate = (pollRate==undefined)?0:pollRate;//A pollrate of 0 means it will be requested once.
5723     this.lastUpdated = 0;
5724     this.behaviour = F.liftBI(
5725         function(value){
5726             return value;
5727         },
5728         function(value){
5729             //log("Upstream Event: "+key);
5730             parent.data = value;
5731             parent.hash = null;
5732             parent.dirty=true;
5733             return [undefined];
5734         },
5735         this.originBehaviour);
5736     this.requiresPoll = function(){
5737         return ((new Date().getTime())>(this.lastUpdated+this.pollRate)||this.lastUpdated==0);
5738     }
5739     this.updateFromServer = function(data, hash){
5740         this.dirty = false;
5741         this.hash = hash;
5742         if(data.length!=0){
5743             this.lastUpdated = new Date().getTime();
5744             this.data = data;
5745             this.event.sendEvent(data);
5746         }
5747     }
5748     this.sendEvent = function(event){
5749         this.behaviour.sendEvent(event);
5750     }
5751     this.key = key;
5752     this.dirty = false;
5753     this.data = initialValue;
5754     this.context = (context==undefined)?"":context;
5755     this.remote = true;
5756     this.newData=null;
5757     var parent = this;
5758 }
5759 
5760 /**
5761  *  CompositKey
5762  * @constructor
5763  */
5764 function CompositKey(key1, key2){
5765     this.getKey = function(){                   
5766         return (key2==undefined||key2.length==0)?key1:key1+"___"+key2;
5767     }
5768     //this["getKey"] = this.buildKey;
5769 }
5770 /**
5771  *  BehaviourManager
5772  * @constructor
5773  */
5774 function BehaviourManager(){
5775     this.availableRemotes = new Array();
5776     this.localData = new Object();
5777     this.data = new Object();
5778     this.buildKey = function(key1, key2){                   
5779         return (key2==undefined||key2.length==0)?key1:key1+"___"+key2;
5780     }
5781     this.getRemote = function(key, context, initialValue, pollRate){
5782         var key2 = key;
5783         if(context=="_"||(context!=undefined&&context!='undefined'&&context!=null&&context.length!=0)){
5784             key2 = new CompositKey(key, context).getKey();
5785         }
5786         initialValue = (initialValue==undefined)?NOT_READY:initialValue;
5787         pollRate = (pollRate==undefined)?0:pollRate;
5788         if(this.data[key2]==undefined)
5789             this.data[key2] =  new RemoteData(key, context, initialValue, pollRate);
5790         else if(this.data[key2].pollRate<pollRate)
5791             this.data[key2].pollRate = pollRate;         
5792         return this.data[key2]; 
5793     }
5794     this.getE = function(key, context){
5795         var key2 = key;
5796         if(context=="_"||(context!=undefined&&context!='undefined'&&context!=null&&context.length!=0)){
5797             key2 = new CompositKey(key, context).getKey();
5798         }
5799         if(this.localData[key2]==undefined)
5800             this.localData[key2] = F.receiverE();
5801         return this.localData[key2];
5802     }
5803     this.getB = function(key, context, initialValue){
5804         var key2 = key;
5805         if(context=="_"||(context!=undefined&&context!='undefined'&&context!=null&&context.length!=0)){
5806             key2 = new CompositKey(key, context).getKey();
5807         }
5808         if(this.localData[key2]==undefined){
5809             this.localData[key2] = F.liftBI(function(value){
5810                 return value;
5811             }, function(value){
5812                 return [value];
5813             }, F.receiverE().startsWith((initialValue==undefined)?NOT_READY:initialValue));
5814         }
5815         return this.localData[key2];
5816     }
5817     /*this.getB = function(key, context){
5818         var key2 = key;
5819         if(context=="_"||(context!=undefined&&context!='undefined'&&context!=null&&context.length!=0)){
5820             key2 = new CompositKey(key, context).getKey();
5821         }
5822         if(this.localData[key2]==undefined)
5823             this.localData[key2] = receiverE().startsWithI(NOT_READY);
5824         return this.localData[key2];
5825     }     */
5826     /*this.registerRemote=function(key){
5827         this.availableRemotes.push(key);
5828     }
5829     this.register=function(key, context, behaviour){
5830         context = (context==undefined||context.length==0)?"_":context;
5831         if(this.localData[key]!=undefined&&this.localData[key][context]!=undefined)
5832             return this.localData[key][context];
5833         if(this.localData[key]==undefined)
5834             this.localData[key] = new Array();
5835         this.localData[key][context] = behaviour;
5836         return this.localData[key][context]; 
5837     }*/
5838     this.deregister = function(key, context){
5839         context = (context=='undefined'||context==null||context.length==0)?"_":context;
5840         key = new CompositKey(key, context).getKey();
5841         this.data[key]=null;
5842         delete this.data[key];
5843     }   
5844     this.isEmpty = function(){
5845         return (this.size()==0);
5846     }
5847     this.size = function(){                 
5848         var size = 0, key;
5849         for (key in this.data) {
5850             if (this.data.hasOwnProperty(key)) size++;
5851         }
5852         return size;
5853         //return Object.keys(this.data).length; 
5854     }
5855     this.get = function(key, context, initialValue){
5856         var mContext = (context==undefined||context.length==0)?"_":context;
5857         if(this.data[key]!=undefined&&this.data[key][mContext]!=undefined){
5858             return this.data[key][mContext];
5859         }
5860         return this.getB(key, context, initialValue);
5861        /* 
5862         
5863         if(this.localData[key]!=undefined&&this.localData[key][mContext]!=undefined)
5864             return this.localData[key][mContext];
5865         if(context=="_"||(context!='undefined'&&context!=null&&context.length!=0)){
5866             key = new CompositKey(key, mContext).getKey();
5867         }
5868         return this.data[key].behaviour; */
5869     }
5870     this.getDataRequest = function(){
5871         var arr = new Array();       
5872         for(var index in this.data){
5873             var dataR = this.data[index];                            //rDatashow
5874             //log(dataR);
5875             if(dataR.requiresPoll()){
5876                 var packet = dataR.dirty?{key: dataR.key, context: dataR.context, data: dataR.data}:{key: dataR.key, context: dataR.context, hash: dataR.hash};
5877                 arr.push(packet);
5878             }
5879         }           
5880         return {"database": cleanFunctions(arr)};
5881     }
5882     this.startPolling = function(){
5883         var localData = this.localData;
5884         var data = this.data;
5885         var respE = F.receiverE();
5886         var requestEvery = window['SETTINGS']['updateWait']; // request with this delay, only if last request is already serviced
5887         var nowB = F.timerB(500); // current time, 500ms granularity
5888         var lastRespTmB = respE.snapshotE(nowB).startsWith(nowB.valueNow());
5889         var requestOkayB = F.liftB(function(now, lastRespTm) {
5890 		//log("Request OK");
5891             return (now > (lastRespTm + requestEvery));                               
5892         }, nowB, lastRespTmB);
5893         var requestReadyE = requestOkayB.changes().filterE(function(x) { return x; }).filterE(function(x){return !DATA.isEmpty()}); 
5894         var dataRequestReady = requestReadyE.snapshotE(nowB).mapE(function(x){return DATA.getDataRequest();}); 
5895         var serverResponseE = sendServerRequestE(dataRequestReady, window['SETTINGS']['scriptPath']+'getBehaviours');
5896         var localSyncE = serverResponseE.mapE(function(retData){                  
5897         	for(key in retData){
5898                 var dataRow = retData[key];
5899                 for(context in dataRow){
5900 	                var newKey = key;
5901 	                if(context!=undefined&&context.length!=0){
5902 	                    newKey+="___"+context;
5903 	                }
5904 	                var serverData = dataRow[context];
5905                     var localData = data[newKey]; 
5906                    //Pre getKey() check for json object contexts. 
5907                     //var newKey = new CompositKey(key, context);
5908                    // localData = (localData!=null)?localData:data[newKey];
5909                     localData.updateFromServer(serverData.data, serverData.hash);
5910                 }                                  
5911             }
5912             respE.sendEvent(true);
5913             return retData;
5914         });
5915         //respE.sendEvent(true);
5916     }
5917 }
5918 function sendServerRequestE(triggerE, url, timeout){
5919     timeout = (timeout==undefined)?15000:timeout;
5920     var rec = F.receiverE();                       
5921     triggerE.mapE(function(requestData){
5922         if(requestData["database"].length>0){
5923         requestData.database = JSON.stringify(requestData.database);
5924         jQuery.ajax({
5925             type: "post",
5926             async: true,
5927             data: requestData,
5928             dataType: 'json',
5929             url: url,
5930             timeout: timeout,
5931             success: function(data){
5932                 rec.sendEvent(data);
5933             },
5934             error: function(data){/*rec.sendEvent(data);*/}
5935         });
5936         }
5937     });                                          
5938     return rec;
5939 }
5940 /**
5941  *  WidgetManager
5942  * @constructor
5943  */
5944 function WidgetManager(){
5945     this.widgetTypes=new Array(); 
5946     this.widgetInterface=new Array();
5947     this.widgets = new Array();
5948     this.register = function(name, classDef, configInterface){
5949         this.widgetTypes[name] = classDef;
5950         if(configInterface!=undefined){
5951             this.widgetInterface[name] = configInterface;
5952         }
5953     }
5954     this.add = function(widget){
5955         this.widgets.push(widget);
5956     }
5957     this.load = function()
5958     {
5959         for(var i=0;i<this.widgets.length;i++){
5960            this.widgets[i].loader();
5961         }
5962     }
5963     this.clear = function(){
5964         this.widgets = new Array();     
5965     }
5966     
5967     //These method are for scripts that are not compiled. String keys are used to avoid abfuscation.
5968     this['getWidgetDef'] = function(str){
5969         return this.widgetTypes[str];
5970     }
5971     this['buildWidget'] = function(widget){
5972         return widget.build();
5973     }
5974     this['renderWidget'] = function(widget, data){
5975         //log(widget);
5976         return (widget['render'])(data);
5977     }
5978     this['loadWidget'] = function(widget){
5979         return widget.loader();
5980     }
5981     this['getWidgetInterface'] = function(name){
5982         return this.widgetInterface[name];
5983     }
5984     this['getWidgetTypes'] = function(){
5985         return this.widgetTypes;
5986     }
5987     this["renderConfigurator"] = function(widget, data){
5988         return widget.render(data);
5989     }
5990     this["getDescription"] = function(widget){
5991         return widget.getDescription();
5992     }
5993     this["getImage"] = function(widget){
5994         log(widget);
5995         return widget.getImage();
5996     }
5997     this["getName"] = function(widget){
5998         return widget.getName();
5999     }
6000     this["getData"] = function(widget){
6001         return widget.getData();
6002     }
6003 }
6004 
6005 
6006 goog['require']('F');
6007 var DATA = new BehaviourManager();
6008 var DOM = new AuroraDom();
6009 var ENUMS = {};
6010 window['WIDGETS'] = new WidgetManager();
6011 var POLL_RATES = {ONCE: 0, VERY_FAST: 500, FAST: 1500, NORMAL: 3000, SLOW: 5000, VERY_SLOW: 30000};
6012 var CONSTANTS = {NOT_READY: 978000,NO_PERMISSION: 978001, RENDER_SIZE: {SMALL: 0, MEDIUM: 1, LARGE: 2}};
6013 var NOT_READY = CONSTANTS.NOT_READY;
6014 var NO_PERMISSION = CONSTANTS.NO_PERMISSION; 
6015 window['UI'] = new aurora_ui();
6016 var WIDGET = {
6017     getWidth: function(){return (data.placeholder==null)?data.width:data.placeholder.style.width.replace('px', '');},
6018     getHeight: function(){return (data.placeholder==null)?data.height:data.placeholder.style.height.replace('px', '');}
6019 }; 
6020 var userB = DATA.getRemote("aurora_current_user",undefined,NOT_READY, POLL_RATES.VERY_SLOW).behaviour;
6021 var widgets=new Array();
6022 var getVars = readGET();
6023 
6024 
6025 //var docReadyE = jQuery(document).fj('extEvtE', 'ready'); 
6026 
6027 /**
6028 * @type {F.Event}
6029 */
6030 var pageE = F.receiverE();
6031 /**
6032 * @type {F.Behavior}
6033 */
6034 var pageB = pageE.startsWith(NOT_READY);
6035 
6036 var pageDataB = F.liftB(function(pageData){
6037     if(pageData==NOT_READY)
6038         return NOT_READY;      
6039     var page = pageData.page;
6040     var theme = pageData.theme;
6041     var permissions = pageData.permissions;
6042     WIDGETS.clear();
6043     //log("Rendering Page "+page+" "+theme);
6044     document.getElementById("body").innerHTML = renderPage(theme.html);   // Using the body div and not body because ckeditor doesnt like the body tag
6045     document.getElementById("content").innerHTML = renderPage(page.html);
6046         
6047     WIDGETS.load();
6048     document.getElementById("body").style.display = 'block';   // Page data is output in php pre JS render but the body div is hidden so its not visible. This is for SEO
6049 },pageB);
6050 ready(function() {
6051     var pageName = window['SETTINGS']['page']['name'];
6052     var href = window['SETTINGS']['scriptPath']+pageName;
6053     if(history.pushState){
6054         //history.pushState({page: pageName}, pageName, href);    
6055     }
6056     else{
6057         //window.location = href;
6058     }  
6059     pageE.delayE(1000).mapE(function(){   //TODO: Fix this dodgey bandaid which fixed the firefox dialog box issue
6060         if(window['SETTINGS']['messages']!=""){
6061             UI.showMessage('', window['SETTINGS']['messages']);
6062             window['SETTINGS']['messages'] = "";      
6063         }
6064     });
6065     pageE.sendEvent({page: window['SETTINGS']['page'], theme: SETTINGS['theme'], permissions: SETTINGS['pagePermissions']});
6066     DATA.startPolling();
6067 });
6068 window.addEventListener('popstate', function(ev) {
6069   if(ev.state && ev.state.page){
6070     loadPageE.sendEvent(ev.state.page);
6071   }
6072   else{
6073     
6074     //loadPageE.sendEvent(document.URL.replace(SETTINGS['scriptPath'], ''))
6075   }
6076 });
6077 //})(F);
6078 
6079 function renderPage(data){
6080     var widgetTypes = WIDGETS.widgetTypes;
6081     widgets=Array();    
6082     var elm = document.createElement('div');
6083     elm.innerHTML=data; 
6084     for (var key in widgetTypes) {
6085         //log(key);
6086         widgetDef = widgetTypes[key];   
6087         var widgetPlaceholders = DOM.getElementsByClassName("widget_"+key, "img", elm);
6088         for (var i=0;i<widgetPlaceholders.length;i++){
6089             if(index==="addEventListener"){
6090                 break;
6091             }
6092             var widgetPlaceholder = widgetPlaceholders[i];     
6093             var instanceId = key+i; //(widgetPlaceholder.id!='')?widgetPlaceholder.id:key+i;
6094             var arguments={};
6095             //alert(widgetPlaceholder.alt);
6096             try{         
6097                 arguments = (widgetPlaceholder.alt==null||widgetPlaceholder.alt=="")?{placeholder: widgetPlaceholder}:window['JSON'].parse(widgetPlaceholder.alt.replaceAll("'", '"'));    
6098             }
6099             catch(err){
6100                 log("Widget Argument Parse Error: "+err);
6101                 arguments={};
6102             }
6103 
6104             var element = document.createElement('span');
6105             if(typeof(arguments)!='string'&&widgetPlaceholder.width!=null&&widgetPlaceholder.width!=null){
6106                 element.width = widgetPlaceholder.width;
6107                 element.height = widgetPlaceholder.height; 
6108             }
6109             arguments.placeholder = widgetPlaceholder;
6110             if(typeof jQuery != 'undefined')
6111                 widget = jQuery.extend(new widgetDef(instanceId, arguments), WIDGET);
6112             else
6113                 widget = new widgetDef(instanceId, arguments);   
6114             WIDGETS.add(widget);
6115             
6116             var wBuild = widget.build();
6117             if(typeof(wBuild)=='undefined'){}
6118             else if(typeof(wBuild)=='string'){
6119                 element.innerHTML = wBuild;
6120             }
6121             else{
6122                 element.appendChild(wBuild);
6123             }
6124             widgetPlaceholder.parentNode.replaceChild(element, widgetPlaceholder);
6125         }
6126     } 
6127     return elm.innerHTML;            
6128 }
6129 
6130 var loadPageE = F.receiverE();
6131 loadPageE.mapE(function(pageName){
6132     ajax({
6133         dataType: 'json',
6134         url: SETTINGS.scriptPath+"request/getPage/"+pageName+"/",
6135         success: function(data){
6136             pageE.sendEvent({page: data, theme: window['SETTINGS']['theme'], permissions: data.permissions});
6137         },
6138         error: connectionError
6139     });    
6140 }); 
6141 function loadPage(pageName){
6142     /*window.location = window['SETTINGS']['scriptPath']+pageName;
6143     return;*/
6144     log("Loadpage");
6145     if(history.pushState){
6146         history.pushState({page: pageName}, pageName, window['SETTINGS']['scriptPath']+pageName);
6147         loadPageE.sendEvent(pageName);
6148     }
6149     else{
6150         window.location = window['SETTINGS']['scriptPath']+pageName;
6151     }
6152     return false;
6153 }   
6154 
6155 function connection_error(error){
6156     log(error);
6157 }
6158 //te2sting testing
6159 function checkPermission(groupId){
6160     for(index in window['SETTINGS']['page']['permissions']['groups']){
6161         if(window['SETTINGS']['page']['permissions']['groups'][index]['group_id']==groupId)
6162             return true;
6163     }
6164     return false;
6165 }
6166 function connectionError(error){
6167     log(error);
6168 }
6169 function isBase(){
6170     return window['SETTINGS']['page']['name']==window['SETTINGS']['defaultPage'];
6171 }
6172 function readGET(){
6173     var params = {};
6174     if(window.location.search){
6175     var param_array = window.location.search.split('?')[1].split('&');
6176     for(var i in param_array){
6177         x = param_array[i].split('=');
6178         params[x[0]] = x[1];
6179     }
6180     return params;
6181 }
6182     return {};
6183 };
6184 
6185 /**
6186  *  aurora_ui
6187  * @constructor
6188  */
6189 function aurora_ui(){
6190     this.active = false;
6191     
6192     this.showOnCursor = function(targetId, text, style, duration){
6193         if(!this.active){
6194             var divId = targetId+'_tooltip';
6195             this.active = true;
6196             var d = DIV({ "className": style,"id": divId,
6197                   style: { "position": 'absolute'}},
6198                 text);
6199             var blah = F.insertDomB(d,targetId,'beginning');
6200             
6201             F.liftB(function(left, top){
6202                 document.getElementById(divId).style.left = (left+5)+'px';
6203                 document.getElementById(divId).style.top = (top+5)+'px';    
6204             }, mouseLeftB(document),mouseTopB(document));
6205                         
6206             if(duration!=null)
6207                 setTimeout(function(){fadeOutE(d, 20, 20).mapE(function(){document.getElementById(targetId).removeChild(d);})}, duration);
6208             this.active = false;
6209             return blah
6210             
6211         }                                  
6212     }
6213     this.showMessage = function(title, message, callback, options){
6214         var modal = (options==undefined||options.modal==undefined)?true:options.modal;
6215         var draggable = (options==undefined||options.draggable==undefined)?false:options.draggable;  
6216         var resizable = (options==undefined||options.resizable==undefined)?false:options.resizable;
6217         var width = (options==undefined||options.width==undefined)?"":options.width;
6218         var height = (options==undefined||options.height==undefined)?"'600'":options.height; 
6219         if(typeof jQuery == 'undefined'){ 
6220             this.dialog(title, message, undefined, callback);
6221         }
6222         else{
6223             var oldD =  document.getElementById('aurora_dialog');
6224             if(oldD!=null)
6225                 oldD.parentNode.removeChild(oldD);
6226             var dialog = createDomElement('div', 'aurora_dialog', '', message);
6227             dialog.style.width = "100%";
6228             dialog.title = title;
6229             document.body.appendChild(dialog);
6230             var dialogOptions = {width: width, "modal": modal,"draggable": draggable,"resizable": resizable,"buttons":[{"text": "Ok","click": function() { jQuery(this).dialog("close");if(callback!=undefined)callback();}}]}
6231             if(options!=undefined && options.fullscreen!=undefined&&options.fullscreen==true){
6232             	dialogOptions.minWidth = 1000;
6233             	dialogOptions.minHeight = jQuery(window).height()-100;
6234         	}
6235             if(options!=undefined&&options.height!=undefined){
6236                 dialogOptions.height = options.height;    
6237             }
6238             jQuery("#aurora_dialog").dialog(dialogOptions);
6239         }
6240     }
6241     this.confirm = function(title, message, text1, callback1, text2, callback2, fullscreen, dialogOpenCallback){
6242         if(typeof jQuery == 'undefined'){
6243             this.dialog(title, message, text1, callback1, text2, callback2, fullscreen, dialogOpenCallback);
6244        }
6245        else{
6246           var options = {
6247             "modal": true,
6248             "draggable": false,
6249             "resizable": false,
6250             "open": function(event, ui) {
6251                 if(dialogOpenCallback!=undefined)
6252                     dialogOpenCallback();
6253             },
6254             "buttons":[
6255             {"text": text1,"click": function(){jQuery(this).dialog("close");if(callback1!=undefined)callback1();}},
6256             {"text": text2,"click": function(){jQuery(this).dialog("close");if(callback2!=undefined)callback2();}}
6257             ]
6258         };
6259         if(fullscreen!=undefined&&fullscreen==true){
6260             options.minWidth = 1000;
6261             options.minHeight = jQuery(window).height()-100;
6262             options.position = ["left","top"];
6263           	options.width = "100%";
6264           	options.height = jQuery(window).height();
6265           	options.zIndex = 1000;
6266         }
6267     
6268         var oldD =  document.getElementById('aurora_dialog');
6269         if(oldD!=null)
6270             oldD.parentNode.removeChild(oldD);
6271         var dialog = createDomElement('div', 'aurora_dialog', '', message);
6272         dialog.title = title;
6273         document.body.appendChild(dialog);
6274         window.top.jQuery("#aurora_dialog").dialog(options);
6275        }
6276     }
6277     
6278     this.dialog = function(title, message, text1, callback1, text2, callback2, fullscreen, dialogOpenCallback){
6279     var dialog = document.createElement('div');
6280     dialog.style.cssText = 'position: absolute; top: 33%; left: 33%; right: 33%; width 33%; background-color: #F0F0F0; padding: 5px;' ;
6281     dialog.innerHTML = message;
6282     var buttonCont = document.createElement('div');  
6283     if(callback1!=undefined){
6284         var button1 = document.createElement('input');
6285         button1.type = 'submit';
6286         button1.value = (text1!=undefined)?text1:"Ok";
6287         button1.onclick = function(){dialog.style.display = 'none';callback1();};
6288         buttonCont.appendChild(button1);
6289     }
6290     if(text1!=undefined&&callback1!=undefined){
6291         var button2 = document.createElement('input');
6292         button2.type = 'submit';
6293         button2.value = text2;
6294         button2.onclick = function(){dialog.style.display = 'none';callback2();};
6295         buttonCont.appendChild(button2); 
6296     }
6297     dialog.appendChild(buttonCont);
6298     document.body.appendChild(dialog);
6299     if(dialogOpenCallback!=undefined)
6300         dialogOpenCallback();         
6301     return dialog;
6302 }
6303 }
6304 
6305 
6306 
6307 //aurora_ui.showOnCursor(targetId, text, style, duration);
6308 
6309 
6310 /* BASE WIDGETS */        
6311 /**
6312  *  WebpageSettingsWidget
6313  * @constructor
6314  */
6315 function WebpageSettingsWidget(instanceId, data){
6316     this.loader=function(){
6317         
6318         var targetPlugin = (data!=undefined&&data.plugin!=undefined)?data.plugin:"aurora";
6319         var themesR = DATA.getRemote("aurora_theme_list", "", NOT_READY, POLL_RATES.VERY_FAST);  //, NOT_READY, POLL_RATES.SLOW 
6320         var dataR = DATA.getRemote("aurora_settings", targetPlugin, NOT_READY, POLL_RATES.VERY_FAST);  //, NOT_READY, POLL_RATES.SLOW    
6321         var dataBI = dataR.behaviour;
6322         //log("loader");
6323         var rendererTypedB = F.liftBI(
6324         function(settingTable, themes){
6325             //log("lift1");  
6326             if(settingTable==NOT_READY||themes==NOT_READY)
6327                 return NOT_READY;
6328             if(settingTable==NO_PERMISSION||themes==NO_PERMISSION)
6329                 return NO_PERMISSION;
6330             //log("lift2");        
6331             //var settingTable = clone(settingTable);
6332             var cellMetaData = [];
6333             for(rowIndex in settingTable["DATA"]){
6334               //  log("Loop: "+rowIndex);
6335                 var cellMetaDataRow = [];
6336                 var name = getTableValue(settingTable, rowIndex, "name"); 
6337                 var type = getTableValue(settingTable, rowIndex, "type");
6338                 var description = getTableValue(settingTable, rowIndex, "description");
6339                 var value = getTableValue(settingTable, rowIndex, "value");
6340                 var valueColIndex = getColumnIndex(settingTable, "value");
6341                                      
6342                 if(CELL_RENDERERS[type]!=undefined){
6343                     var renderer = new BasicCellRenderer(type, name);   
6344                     cellMetaDataRow[valueColIndex] = {"renderer": renderer};    
6345                 }
6346                 else if(type=="userDisplay"){
6347                     var options = [{"display": "Username", value: 1}, {"display": "Firstname", "value": 2}, {"display": "Full Name", "value": 3}];
6348                     var renderer = new BasicRadioCellRendererContainer(name, options);
6349                     cellMetaDataRow[valueColIndex] = {"renderer": renderer};  
6350                 }
6351                 else if(type=="themeSelect"){
6352                     var options = [];
6353                     for(rowId in themes["DATA"]){
6354                         var themeId = getTableValue(themes, rowId, "theme_id");
6355                         var themeName = getTableValue(themes, rowId, "theme_name");
6356                         options.push({"display": themeName, "value": themeId});
6357                     }
6358                     var renderer = new BasicSelectCellRendererContainer(options);
6359                     cellMetaDataRow[valueColIndex] = {"renderer": renderer};            
6360                 }
6361                 cellMetaData.push(cellMetaDataRow);
6362             }
6363             settingTable["CELLMETADATA"] = cellMetaData;
6364             //log("Lift Return");
6365             return settingTable;
6366         },
6367         function(settingTable, themes){
6368            // var settingTable = clone(settingTable);
6369             return [settingTable, undefined];
6370         },
6371         dataBI, themesR.behaviour);   
6372         tableBI = TableWidgetB(instanceId+"_table", data, rendererTypedB);    
6373         F.insertDomB(tableBI, instanceId+"_container");
6374     
6375     }
6376     this.destroy=function(){
6377         DATA.deregister("aurora_settings", "");
6378     }
6379     this.build=function(){
6380         return "<span id=\""+instanceId+"_container\"> </span>";
6381     }
6382 }     
6383 WIDGETS.register("WebpageSettingsWidget", WebpageSettingsWidget); 
6384 /**
6385  *  GroupsManagerWidget
6386  * @constructor
6387  */
6388 function GroupsManagerWidget(instanceId, data){
6389     this.loader=function(){
6390         var dataR = DATA.getRemote("aurora_groups", "", NOT_READY, POLL_RATES.VERY_FAST);  //, NOT_READY, POLL_RATES.SLOW    
6391         tableB = TableWidgetB(instanceId+"_table", data, dataR.behaviour);    
6392         F.insertDomB(tableB, instanceId+"_container");
6393     }
6394     this.destroy=function(){
6395         DATA.deregister("aurora_groups", "");
6396     }
6397     this.build=function(){
6398         return "<span id=\""+instanceId+"_container\"> </span>";
6399     }
6400 }     
6401 WIDGETS.register("GroupsManagerWidget", GroupsManagerWidget);
6402 /**
6403  *  PluginManagerWidget
6404  * @constructor
6405  */
6406 function PluginManagerWidget(instanceId, data){
6407     
6408     this.loader=function(){
6409         var dataR = DATA.getRemote("aurora_plugins", "", NOT_READY, POLL_RATES.VERY_FAST);  //, NOT_READY, POLL_RATES.SLOW
6410         tableB = TableWidgetB(instanceId+"_table", data, dataR.behaviour);    
6411         F.insertDomB(tableB, instanceId+"_container");
6412     }
6413     this.destroy=function(){
6414         DATA.deregister("aurora_plugins", "");
6415     }
6416     this.build=function(){
6417         return "<span id=\""+instanceId+"_container\"> </span>";
6418     }
6419 }     
6420 WIDGETS.register("PluginManagerWidget", PluginManagerWidget);
6421 
6422 /**
6423  *  BehaviourPermissionsWidget
6424  * @constructor
6425  */
6426 function BehaviourPermissionsWidget(instanceId, data){      
6427     this.loader=function(){
6428     	var groupsR = DATA.getRemote("aurora_groups", "", NOT_READY, POLL_RATES.VERY_FAST);
6429     	var behavioursR = DATA.getRemote("aurora_permissions", "", NOT_READY, POLL_RATES.VERY_FAST);
6430         var behaviourPermissionsR = DATA.getRemote("aurora_permissions_set", "", NOT_READY, POLL_RATES.VERY_FAST);  
6431         
6432 	    var groupsB = groupsR.behaviour;
6433         var behavioursB = behavioursR.behaviour;
6434         var newTableB = F.liftBI(function(behaviourPermissions, groups, behaviours){   	
6435 	        if(groups==NOT_READY||behaviours==NOT_READY||behaviourPermissions==NOT_READY)
6436                 return NOT_READY;
6437             if(groups==NO_PERMISSION||behaviours==NO_PERMISSION||behaviourPermissions==NO_PERMISSION)
6438                 return NO_PERMISSION;
6439             var columns = [{"reference": "behaviour", "display": "", "type": "string", "visible":true, "readOnly": false}];
6440             var groupColMap = new Array();
6441             var count = 1;
6442             for(groupIndex in groups["DATA"]){
6443                 var groupId = getTableValue(groups, groupIndex, "groupId");
6444                 var groupName = getTableValue(groups, groupIndex, "group");
6445         	    //var group = groups["DATA"][groupIndex];
6446         	    columns.push({"reference": groupId, "display": groupName,"visible":true, "readOnly": false});
6447         	    groupColMap[groupId+""] = count++;
6448             }
6449             var data = [];
6450             var rowMetaData = [];
6451             var cellMetaData = [];
6452             var columnMetaData = [];
6453             columnMetaData[0] = {"permissions": "R"};
6454             for(behaviourIndex in behaviours["DATA"]){
6455         	    var behaviour = behaviours["DATA"][behaviourIndex];
6456         	    var behaviourId = getTableValue(behaviours, behaviourIndex, "permissionRegisterId");
6457                 var permissionRegType = getTableValue(behaviours, behaviourIndex, "type");
6458                 var typeRenderer = new BasicCellRenderer(permissionRegType);
6459                 var behaviourDescription = getTableValue(behaviours, behaviourIndex, "description");
6460            		var dataRow = [behaviourDescription];
6461            		var cellMetaDataRow = [];
6462                 for(groupIndex in groups["DATA"]){           
6463                     cellMetaDataRow[parseInt(groupIndex)+1] = {"renderer": typeRenderer}; 
6464                 }
6465         	    for(permissionIndex in behaviourPermissions["DATA"]){
6466         		    var bPermissionsBehaviourId = getTableValue(behaviourPermissions, permissionIndex, "permissionRegisterId");
6467                     if(behaviourId==bPermissionsBehaviourId){
6468         			    var bPermission = behaviourPermissions["DATA"][permissionIndex];
6469 				        var bPermissionId = getTableValue(behaviourPermissions, permissionIndex, "permissionId");
6470            				var bPermissionGroupId = getTableValue(behaviourPermissions, permissionIndex, "groupId");
6471            				var bPermissionPermission = getTableValue(behaviourPermissions, permissionIndex, "permissions");
6472         			    var colIndex = groupColMap[bPermissionGroupId+""];
6473                         //alert(colIndex);
6474                         if(bPermissionPermission=="true"||bPermissionPermission=="false"){
6475                             bPermissionPermission = auroraParseBoolean(bPermissionPermission);
6476                         }
6477         			    dataRow[colIndex] = bPermissionPermission;
6478                         if(cellMetaDataRow[colIndex]==undefined){
6479                             cellMetaDataRow[colIndex] = {"permissionId":bPermissionId};
6480                         }
6481                         else{
6482                         cellMetaDataRow[colIndex]["permissionId"] = bPermissionId;
6483                         }
6484                         if(bPermissionGroupId==3&&(bPermissionsBehaviourId==2||bPermissionsBehaviourId==4||bPermissionsBehaviourId==5))
6485                             cellMetaDataRow[colIndex]["permissions"] = {"canEdit": false};
6486         		    }
6487         	    }
6488         	    cellMetaData.push(cellMetaDataRow);
6489         	    data.push(dataRow);
6490         	    rowMetaData.push(behaviourId);
6491             }
6492 	        var table = {"DATA": data, "COLUMNS": columns, "TABLEMETADATA": {"originalColumns": behaviourPermissions["COLUMNS"], "permissions": {"canAdd": false, "canDelete": false, "canEdit": true}}, "ROWMETADATA": rowMetaData, "CELLMETADATA": cellMetaData, "COLUMNMETADATA": columnMetaData};
6493             return table;
6494         },
6495         function(value){
6496         	var permissionsData = value["DATA"];
6497         	var newData = [];
6498         	for(rowIndex in permissionsData){
6499         		newRow = [];
6500         		var row = permissionsData[rowIndex];
6501         		var behaviourName = row[0];
6502         		var behaviourId = value["ROWMETADATA"][rowIndex];
6503         		for(colIndex in value["COLUMNS"]){
6504         			if(colIndex==0)
6505         				continue;
6506         			var dataIndex = parseInt(colIndex)+1;
6507         			var column = value["COLUMNS"][colIndex];
6508         			var groupId = column["reference"];
6509         			var dataCell = row[colIndex];
6510         			if(dataCell!=undefined){
6511         			   //log(value["CELLMETADATA"][rowIndex][colIndex]);
6512                        /* log("RI: "+rowIndex);
6513                         log("CI: "+colIndex);
6514                         log("permissionId: "+value["CELLMETADATA"][rowIndex][colIndex]["permissionId"]);
6515                         log(value["CELLMETADATA"][rowIndex][colIndex]["permissionId"]);
6516                         for(index in value["CELLMETADATA"][rowIndex][colIndex]){
6517                             log("Index: "+index);
6518                         }
6519                         log("");*/
6520                         var id=(value["CELLMETADATA"][rowIndex][colIndex]!=undefined&&value["CELLMETADATA"][rowIndex][colIndex]["permissionId"]!=undefined)?value["CELLMETADATA"][rowIndex][colIndex]["permissionId"]:"NULL";
6521         				///log("ID: "+id+", RI:"+rowIndex+", CI:"+colIndex);
6522                         newData.push([id, behaviourId, groupId, undefined, dataCell]);
6523         			}
6524         		}		
6525         	}
6526         	var newTable = {"DATA": newData, "COLUMNS": value["TABLEMETADATA"].originalColumns, "TABLEMETADATA": {"permissions": {"canAdd": false, "canDelete": false, "canEdit": true}}, "ROWMETADATA": [], "CELLMETADATA": [], "COLUMNMETADATA": []};
6527 		return [newTable, undefined,undefined];		
6528         },
6529         behaviourPermissionsR.behaviour, groupsB, behavioursB);        
6530         tableB = TableWidgetB(instanceId+"_table", data, newTableB);    
6531         F.insertDomB(tableB, instanceId+"_container");
6532     }
6533     this.destroy=function(){
6534         DATA.deregister("aurora_groups", "");
6535         DATA.deregister("aurora_permissions", "");
6536         DATA.deregister("aurora_permissions_set", "");
6537         
6538     }
6539     this.build=function(){
6540         return "<span id=\""+instanceId+"_container\"> </span>";
6541     }
6542 }     
6543 WIDGETS.register("BehaviourPermissionsWidget", BehaviourPermissionsWidget);
6544 
6545 /**
6546  *  AuroraUserGroupColumn
6547  * @constructor
6548  */
6549 function AuroraUserGroupColumn(groups){
6550     this.groups = groups;
6551     this.getCellRenderer = function(value, cell, width){
6552 	    if(cell==undefined){
6553 		    //alert("caller is " + arguments.callee.caller.toString());
6554 		    return null;
6555 	    }	   
6556         return new AuroraGroupCellRenderer(groups, value, cell, width);    
6557     }
6558 }
6559 /**
6560  *  AuroraGroupCellRenderer
6561  * @constructor
6562  */
6563 function AuroraGroupCellRenderer(groups, value, cell, width){
6564     var select = document.createElement("select");
6565     var index;
6566     cell.className="TableWidgetCell";
6567     for(index in groups){
6568                 var group = groups[index];
6569                 var option=document.createElement("OPTION");
6570                 option.appendChild(document.createTextNode(group[1]));
6571                 option.value = group[0];
6572                 select.appendChild(option);       
6573             }
6574             select.value = value;     
6575     this.render = function(){
6576         select.disabled = true;
6577         cell.removeChildren();
6578         cell.appendChild(select);    
6579     }
6580     this.renderEditor = function(){
6581         select.disabled = false;  
6582         cell.removeChildren();
6583         cell.appendChild(select);
6584     }
6585     this.setSelected = function(selected){
6586         if(selected){
6587             cell.className="TableWidgetCellSelected"; 
6588         }
6589         else
6590             cell.className="TableWidgetCell"; 
6591     }
6592     this.getValue = function(){
6593         return select.value;
6594     }
6595     this.setValue = function(newValue){
6596         select.value = newValue;
6597     }
6598     this.getUpdateEvent = function(){;
6599         return F.extractValueE(select);
6600     }
6601 }             
6602 /**
6603  *  UsersManagerWidget
6604  * @constructor
6605  */                                               
6606 function UsersManagerWidget(instanceId, data){
6607     
6608     this.loader=function(){
6609         var dataR = DATA.getRemote("aurora_users", "", NOT_READY, POLL_RATES.VERY_FAST);  //, NOT_READY, POLL_RATES.SLOW
6610         var groupsR = DATA.getRemote("aurora_groups", "", NOT_READY, POLL_RATES.VERY_FAST); //, NOT_READY, POLL_RATES.SLOW
6611         var renderedTableB = F.liftBI(function(data, groups){
6612             if(data==NOT_READY||groups==NOT_READY)
6613                 return NOT_READY;
6614             for(colIndex in data["COLUMNS"]){
6615                 if(data["COLUMNS"][colIndex]["reference"]=="group"){
6616                     if(data["COLUMNMETADATA"][colIndex]==undefined)
6617                         data["COLUMNMETADATA"][colIndex] = {};
6618                     data["COLUMNMETADATA"][colIndex]["renderer"] = new AuroraUserGroupColumn(groups["DATA"]);
6619                 }
6620             
6621             }
6622             //showObj(data);
6623             return data;
6624         },function(value){
6625             return [value, null];
6626         }, dataR.behaviour, groupsR.behaviour);
6627     
6628     tableB = TableWidgetB(instanceId+"_table", data, renderedTableB);    
6629     F.insertDomB(tableB, instanceId+"_container");
6630     
6631     }
6632     this.destroy=function(){
6633         DATA.deregister("aurora_users", "");
6634         DATA.deregister("aurora_groups", "");
6635     }
6636     this.build=function(){
6637         return "<span id=\""+instanceId+"_container\"> </span>";
6638     }
6639 }     
6640 function auroraBaseFindCustomRendererForCol(renderers, colIndex){
6641     for(var index in renderers){
6642         if(renderers[index].columnIndex==colIndex)
6643             return renderers[index];
6644     }
6645     return undefined;
6646 }          
6647 WIDGETS.register("UsersManagerWidget", UsersManagerWidget);     
6648 
6649 /**
6650  *  HTMLSelectWidget
6651  * @constructor
6652  */ 
6653 function HTMLSelectWidget(instanceId, userData){
6654     /*var width = (data.placeholder!=undefined&&data.placeholder.style.width!=undefined)?data.placeholder.style.width:undefined;
6655     var height = (data.placeholder!=undefined&&data.placeholder.style.height!=undefined)?data.placeholder.style.height:undefined;
6656     */
6657     var id = instanceId+"_container";
6658     var container = createDomElement("div", id);
6659     container.className = "HTMLSelectWidget";
6660     container.style.overflow = 'auto';
6661     this.rowSelectionsB = undefined;
6662     this.loader=function(){
6663         var dataB = userData['dataB'];
6664         var htmlDataB = dataB.liftB(function(data){
6665             var cont = document.createElement("div");
6666             for(index in data){
6667                 var optionValue = data[index].value;
6668                 var optionHTML = data[index].display;
6669                 var optionElement = createDomElement("div",undefined, "HTMLSelectWidgetOption",optionHTML);
6670                 optionElement.id = "HTMLSelectWidgetOption_"+index;
6671                 //cont.appendChild(optionElement);
6672                 container.appendChild(optionElement);
6673             }
6674             return container;
6675         });
6676         F.insertDomB(htmlDataB, id);
6677        var optionClickedE = jQuery(container).fj('extEvtE', 'click').mapE(function(ev){
6678             var target = (ev.target==undefined)?ev.srcElement:ev.target;
6679             while(target.parentNode!=undefined){
6680                 if(target.className=="HTMLSelectWidgetOption"||target.className=="HTMLSelectWidgetOptionSelected"){
6681                     var clicked = parseInt(target.id.replace("HTMLSelectWidgetOption_", ""));
6682                     return clicked;
6683                 }
6684                 target = target.parentNode; 
6685             }
6686        });
6687        
6688        
6689        var rowSelectionsE = optionClickedE.collectE([],function(newElement,arr) {
6690         if(newElement==NOT_READY)
6691             return []; 
6692            // log("Col");
6693            var clickedIndex = newElement;
6694             if(arr.length==1&&arrayContains(arr, clickedIndex)){
6695                 arr = [];
6696             }
6697             else{
6698                 arr = [clickedIndex];
6699             }
6700         return arr;
6701         });
6702         this.selected = F.liftB(function(optionData, rowSelections){
6703             if(optionData==NOT_READY||rowSelections==NOT_READY)
6704                 return NOT_READY;
6705             for(index in optionData){
6706                 document.getElementById("HTMLSelectWidgetOption_"+index).className = "HTMLSelectWidgetOption";    
6707             }
6708             if(rowSelections.length==1){
6709                 var selectedIndex = rowSelections[0];
6710                 document.getElementById("HTMLSelectWidgetOption_"+selectedIndex).className = "HTMLSelectWidgetOptionSelected";
6711                 return optionData[selectedIndex].value;
6712             }
6713             return NOT_READY;
6714         }, dataB, rowSelectionsE.startsWith(NOT_READY));
6715     }
6716     this.destroy=function(){
6717 
6718     }
6719     this.build=function(){
6720         return "<div id=\""+id+"\"> </div>";
6721     }
6722     this['selectedValue'] = function(){return this.selected.valueNow()};
6723 }
6724 WIDGETS.register("HTMLSelectWidget", HTMLSelectWidget);  
6725 
6726 /**
6727  *  StringBuilderEx
6728  * @constructor
6729  */
6730 StringBuilderEx = function(){
6731     this._buffer = new Array();
6732 }
6733 
6734     StringBuilderEx.prototype =
6735     {
6736     // This method appends the string into an array 
6737         append : function(text)
6738         {
6739             this._buffer[this._buffer.length] = text;
6740         },
6741         
6742     // This method does concatenation using JavaScript built-in function
6743         toString : function()
6744         {
6745             return this._buffer.join("");
6746         }
6747     }; 
6748     
6749 /**
6750  *  FirstNameWidget
6751  * @constructor
6752  */ 
6753 function FirstNameWidget(instanceId, data){
6754     this.loader=function(){}
6755     this.destroy=function(){}
6756     this.build=function(){
6757         return "<span id=\""+instanceId+"_container\">"+window['SETTINGS']['user']['firstname']+"</span>"; 
6758     }                         
6759 } 
6760 /**
6761  *  FirstNameWidgetConfigurator
6762  * @constructor
6763  */ 
6764 function FirstNameWidgetConfigurator(){
6765     this['load'] = function(newData){}
6766     this['build'] = function(newData){}
6767     this['getData'] = function(){}
6768     this['getName'] = function(){
6769         return "First Name Widget";
6770     }
6771     this['getDescription'] = function(){
6772         return "Text showing the current users first name";
6773     }
6774     this['getPackage'] = function(){
6775         return "Users";
6776     }
6777 } 
6778 WIDGETS.register("FirstNameWidget", FirstNameWidget, FirstNameWidgetConfigurator); 
6779 
6780 /**
6781  *  FullNameWidget
6782  * @constructor
6783  */ 
6784 function FullNameWidget(instanceId, data){
6785     this.loader=function(){}
6786     this.destroy=function(){}
6787     this.build=function(){
6788         return "<span id=\""+instanceId+"_container\">"+window['SETTINGS']['user']['firstname']+" "+window['SETTINGS']['user']['lastname']+"</span>"; 
6789     }                         
6790 }   
6791 /**
6792  *  FullNameWidgetConfigurator
6793  * @constructor
6794  */ 
6795 function FullNameWidgetConfigurator(){
6796     this['load'] = function(newData){}
6797     this['build'] = function(newData){}
6798     this['getData'] = function(){}
6799     this['getName'] = function(){
6800         return "Last Name Widget";
6801     }
6802     this['getDescription'] = function(){
6803         return "Text showing the current users last name";
6804     }
6805     this['getPackage'] = function(){
6806         return "Users";
6807     }
6808 } 
6809 WIDGETS.register("FullNameWidget", FullNameWidget, FullNameWidgetConfigurator); 
6810 
6811 /**
6812  *  UsernameWidget
6813  * @constructor
6814  */ 
6815 function UsernameWidget(instanceId, data){
6816     this.loader=function(){}
6817     this.destroy=function(){}
6818     this.build=function(){
6819         return "<span id=\""+instanceId+"_container\">"+window['SETTINGS']['user']['username']+"</span>"; 
6820     }                         
6821 }
6822 
6823 /**
6824  *  UsernameWidgetConfigurator
6825  * @constructor
6826  */                                                      
6827 function UsernameWidgetConfigurator(){
6828     this['load'] = function(newData){}
6829     this['build'] = function(newData){}
6830     this['getData'] = function(){}
6831     this['getName'] = function(){
6832         return "User Name Widget";
6833     }
6834     this['getDescription'] = function(){
6835         return "Text showing the current users user name";
6836     }
6837     this['getPackage'] = function(){
6838         return "Users";
6839     }
6840     this['getImage'] = function(){}
6841 } 
6842 WIDGETS.register("UsernameWidget", UsernameWidget, UsernameWidgetConfigurator); 
6843 //HASHffff
6844 
6845 
6846 /**
6847  *  LoggedInImageWidget
6848  * @constructor
6849  */ 
6850 function LoggedInImageWidget(instanceId, data){
6851     var href = (window['SETTINGS']['user']['groupid']==1)?data.outURL:data.inURL;
6852     var src = (window['SETTINGS']['user']['groupid']==1)?data.outSRC:data.inSRC;
6853     this.loader=function(){
6854         /*setTimeout(function(){
6855             document.getElementById(instanceId+"_anchor").setAttribute('href',href);
6856             document.getElementById(instanceId+"_img").setAttribute('onclick',function(){window.location('/logout');});
6857             document.getElementById(instanceId+"_img").setAttribute('style',"cursor: pointer;");
6858         }, 1000);  */
6859     }
6860     this.destroy=function(){}
6861     
6862     this.build=function(){
6863         return "<a id=\""+instanceId+"_anchor\" href=\""+href+"\"><img id=\""+instanceId+"_img\" src=\""+src+"\" alt=\"\" /></a>";
6864     }                         
6865 }
6866 WIDGETS.register("LoggedInImageWidget", LoggedInImageWidget);
6867 
6868 /**
6869  *  LoggedInImageMenuWidget
6870  * @constructor
6871  */ 
6872 function LoggedInImageMenuWidget(instanceId, data){
6873     this.loader=function(){                
6874         var li = document.createElement('li');
6875         if(data.targetGroupId==undefined){
6876             var src = (window['SETTINGS']['user']['groupid']!=1)?data.inSRC:data.outSRC;
6877             var url = (window['SETTINGS']['user']['groupid']!=1)?data.inURL:data.outURL;    
6878         } 
6879         else{                
6880             var targetGroupId = data.targetGroupId;             
6881             var src = (window['SETTINGS']['user']['groupid']==targetGroupId)?data.inSRC:data.outSRC;
6882             var url = (window['SETTINGS']['user']['groupid']==targetGroupId)?data.inURL:data.outURL;
6883         }
6884         li.innerHTML = "<a id=\""+instanceId+"_anchor\" href=\""+url+"\"><img id=\""+instanceId+"_img\" src=\""+src+"\" alt=\"\" /></a>";           
6885         jQuery(li).prependTo(jQuery("#"+data.target));
6886     }
6887     this.destroy=function(){}
6888     
6889     this.build=function(){}                         
6890 }
6891 WIDGETS.register("LoggedInImageMenuWidget", LoggedInImageMenuWidget);
6892 
6893 
6894 
6895 /**
6896  *  UserGroupDivHiderWidget
6897  * @constructor                         
6898  */ 
6899 function UserGroupDivHiderWidget(instanceId, data){
6900 
6901     
6902     this.loader=function(){
6903         var targetDiv = DOM.get(data.target);
6904         var visibleGroups = data.visibleGroups;
6905         userB.liftB(function(user){
6906             if(!good())
6907                 return NOT_READY;
6908             if(arrayContains(visibleGroups, parseInt(user.group_id))){
6909                 jQuery(targetDiv).fadeIn(300);
6910                    
6911             }
6912             else{
6913                 jQuery(targetDiv).fadeOut(300);  
6914             }
6915         });                                   
6916     }
6917     this.destroy=function(){}
6918     
6919     this.build=function(){
6920         return "";
6921     }                         
6922 }
6923 WIDGETS.register("UserGroupDivHiderWidget", UserGroupDivHiderWidget);
6924 
6925 
6926 
6927 /**
6928  *  FileSizeRenderer
6929  * @constructor
6930  */
6931 function FileSizeRenderer(value, cell, width){
6932     var container = DOM.createDiv();
6933     cell.appendChild(container);
6934     
6935     this.render = function(){
6936     }
6937     this.renderEditor = function(){        
6938     }
6939     this.setSelected = function(selected){
6940         if(selected){
6941             cell.className="TableWidgetCellSelected"; 
6942         }                                  
6943         else{
6944             cell.className="TableWidgetCell"; 
6945         }
6946     }
6947     this.getValue = function(){
6948         return value; //force readonly for now.
6949         var val = container.innerHTML;
6950         if(val.length==0){
6951             val = -1;
6952         }
6953         else{
6954             val = parseInt(val);
6955         }
6956         return val;
6957     }
6958     this.setValue = function(newValue){
6959         if(newValue<0||newValue==""){
6960             newValue = "";
6961         }
6962         else if(newValue>1000000000000000){
6963             newValue = ((newValue/1000000000000000).toFixed(2))+" PB";
6964         }
6965         else if(newValue>1000000000000){
6966             newValue = ((newValue/1000000000000).toFixed(2))+" TB";
6967         }
6968         else if(newValue>1000000000){
6969             newValue = ((newValue/1000000000).toFixed(2))+" GB";
6970         }
6971         else if(newValue>1000000){
6972             newValue = ((newValue/1000000).toFixed(2))+" MB";
6973         }
6974         else if(newValue>1000){
6975             newValue = ((newValue/1000).toFixed(2))+" KB";
6976         }
6977         else{
6978             newValue = newValue+" B";
6979         }
6980         container.innerHTML = newValue;
6981     }
6982     this.getUpdateEvent = function(){
6983         return F.zeroE();
6984     }
6985     this.setValue(value);
6986 }
6987 
6988 /**
6989  *  FileSizeRendererColumn
6990  * @constructor
6991  */
6992 function FileSizeRendererColumn(){
6993     this.getCellRenderer = function(value, cell, width){
6994         if(cell==undefined){
6995             return null;
6996         }       
6997         return new FileSizeRenderer(value, cell, width);    
6998     }
6999 }
7000 
7001 
7002 
7003 
7004 
7005 
7006 /**
7007  *  FileTypeRenderer
7008  * @constructor
7009  */
7010 function FileTypeRenderer(value, cell, width){
7011     var img = DOM.createImg(undefined, undefined, window["SETTINGS"]["scriptPath"]+"resources/trans.png");
7012     cell.appendChild(img);
7013     cell.style.textAlign="center";
7014     this.render = function(){
7015     }
7016     this.renderEditor = function(){        
7017     }
7018     this.setSelected = function(selected){
7019         if(selected){
7020             cell.className="TableWidgetCellSelected"; 
7021         }                                  
7022         else{
7023             cell.className="TableWidgetCell"; 
7024         }
7025     }
7026     this.getValue = function(){
7027         return value;
7028     }
7029     this.setValue = function(val){
7030         var src="";
7031         if(val==undefined){
7032         }
7033         else if(val=="directory"){                
7034             src=window["SETTINGS"]["theme"]["path"]+"tables/directory.png";
7035         }
7036         else if(val.contains("image")){                
7037             src=window["SETTINGS"]["theme"]["path"]+"tables/image.png";
7038         }
7039         else if(val.contains("video")){                
7040             src=window["SETTINGS"]["theme"]["path"]+"tables/video.png";
7041         }
7042         else if(val.contains("audio")){                
7043             src=window["SETTINGS"]["theme"]["path"]+"tables/music.png";
7044         }
7045         else if(val.contains("text")){                
7046             src=window["SETTINGS"]["theme"]["path"]+"tables/document.png";
7047         }
7048         else if(val.contains("torrent")){                
7049             src=window["SETTINGS"]["theme"]["path"]+"tables/torrent.png";
7050         }
7051         else if(val.contains("zip")){                
7052             src=window["SETTINGS"]["theme"]["path"]+"tables/zip.png";
7053         }
7054         else if(val.contains("g-zip")){                
7055             src=window["SETTINGS"]["theme"]["path"]+"tables/gzip.png";
7056         }
7057         else if(val.contains("excel")){                
7058             src=window["SETTINGS"]["theme"]["path"]+"tables/excel.png";
7059         }
7060         else if(val.contains("word")){                
7061             src=window["SETTINGS"]["theme"]["path"]+"tables/word.png";
7062         }
7063         else if(val.contains("font")){                
7064             src=window["SETTINGS"]["theme"]["path"]+"tables/font.png";
7065         }
7066         else if(val.contains("pdf")){                
7067             src=window["SETTINGS"]["theme"]["path"]+"tables/pdf.png";
7068         }
7069         else if(val.contains("kml")){                
7070             src=window["SETTINGS"]["theme"]["path"]+"tables/kml.png";
7071         }
7072         if(src!=""){
7073             img.src = src;
7074         }
7075     }
7076     this.getUpdateEvent = function(){
7077         return F.zeroE();
7078     }
7079     this.setValue(value);
7080 }
7081 /**
7082  *  FileTypeRendererColumn
7083  * @constructor
7084  */
7085 function FileTypeRendererColumn(){
7086     this.getCellRenderer = function(value, cell, width){
7087         if(cell==undefined){
7088             return null;
7089         }       
7090         return new FileTypeRenderer(value, cell, width);    
7091     }
7092 }
7093 function good(){
7094     var args = arguments.callee.caller.arguments;
7095     for(index in args){
7096         if(args[index]==NOT_READY)
7097             return false;
7098     }
7099     return true;
7100 }
7101 function liftBArray(f, argsF){
7102     argsF.unshift(f);
7103     var behaviour = F.liftB.apply(argsF[0], argsF);
7104     return behaviour;
7105 }
7106 function funcCallArray(f, argsF){
7107     var behaviour = f.apply(this, argsF);
7108 } 
7109 function jFadeInE(triggerE, elementId, time){
7110     var rec = receiverE();
7111     triggerE.mapE(function(event){
7112         jQuery(document.getElementById(elementId)).fadeIn(time, function(){rec.sendEvent(event);});
7113     });
7114     return rec;
7115 }
7116 
7117 function FileReaderLoadedE(fr){
7118     var rec = receiverE();
7119     fr.onload = function(event){
7120         rec.sendEvent(event);    
7121     }
7122     return rec;
7123 }
7124 function fileDragDropE(element){
7125     var rec = receiverE();
7126     element.addEventListener('drop', function(event){
7127             event.stopPropagation();  
7128             event.preventDefault();
7129             rec.sendEvent(event);
7130             //handleDragAndDrogUpload(event);
7131     }, false);
7132     return rec;
7133     //return extractEventE(element, 'drop');    
7134 }
7135 function fileDropEnterE(element){
7136     var rec = receiverE();
7137     element.addEventListener('dragenter', function(event){
7138             event.stopPropagation();  
7139             event.preventDefault();
7140             rec.sendEvent(event);
7141             //handleDragAndDrogUpload(event);
7142     }, false);
7143     return rec;    
7144 }
7145 function fileDragOverE(element){
7146     var rec = receiverE();
7147     element.addEventListener('dragover', function(event){
7148             event.stopPropagation();  
7149             event.preventDefault();
7150             rec.sendEvent(event);
7151             //handleDragAndDrogUpload(event);
7152     }, false);
7153     return rec;    
7154 }
7155 function getAjaxRequestE(triggerE, url, timeout){
7156     timeout = (timeout==undefined)?15000:timeout;
7157     var rec = F.receiverE();      
7158                        
7159     triggerE.mapE(function(requestData){
7160         
7161         jQuery.ajax({
7162             type: "post",
7163             data: requestData,
7164             dataType: 'json',
7165             url: url,
7166             timeout: timeout,
7167             success: function(data){
7168                 rec.sendEvent(data);
7169             },
7170             error: function(data){/*rec.sendEvent(data);*/}
7171         });
7172     });                                          
7173     return rec;
7174 }
7175 function getAjaxRequestB(triggerB, url){
7176     var rec = F.receiverE();                     
7177     triggerB.liftB(function(requestData){
7178         if(requestData!=NOT_READY){                                 
7179         jQuery.ajax({
7180             type: "post",
7181             data: requestData,
7182             dataType: 'json',
7183             url: url.replace("<VAL>", requestData),
7184             success: function(data){
7185                 rec.sendEvent(data);
7186             },
7187             error: function(data){rec.sendEvent(data);}
7188         });
7189         }
7190     });                                          
7191     return rec;
7192 }
7193 function FileReaderReadyE(fr){
7194     var rec = receiverE();
7195     fr.onload = function(event){
7196         rec.sendEvent(event.target.result);
7197     }
7198     return rec;
7199 }     
7200 function getAjaxFileRequest(triggerE, url, contentType){
7201     var rec = F.receiverE();
7202     triggerE.mapE(function(builder){
7203         var xhr = new XMLHttpRequest();
7204         xhr.open("POST", url, true);
7205         xhr.setRequestHeader('Content-Type', contentType);
7206         //xhr.send(builder);
7207         xhr.sendAsBinary(builder);        
7208         xhr.onload = function(event) { 
7209             if (xhr.responseText)
7210                 rec.sendEvent(JSON.parse(xhr.responseText));
7211         };
7212     });
7213     return rec;
7214 }
7215 
7216 function AuroraTaskQueue(dequeueEventE){ 
7217     return new AuroraTaskQueueStack(dequeueEventE, "queue");
7218 }
7219 function AuroraTaskStack(dequeueEventE){ 
7220     return new AuroraTaskQueueStack(dequeueEventE, "stack");
7221 }
7222 function AuroraTaskQueueStack(dequeueEventE, type){
7223     var taskqueustack = this;
7224     var collectionType = (type==undefined)?"stack":"queue";
7225     this.enqueueE = F.receiverE();
7226    
7227    this.dequeueEventE = dequeueEventE;
7228    this.push = function(val){
7229     this.enqueueE.sendEvent(val); 
7230    };
7231    this.enqueue = function(val){
7232     this.enqueueE.sendEvent(val);
7233    };
7234   
7235   
7236    var dequeueEventE = F.receiverE();
7237    this.dequeueEventE = dequeueEventE;
7238    var finishedE = F.receiverE();
7239    this.finishedE = finishedE.filterE(function(val){return val;});
7240    var finishedB = finishedE.filterRepeatsE().startsWith(true);
7241    var startQueueE = F.receiverE();
7242    
7243    this.jobQueueE = F.mergeE(this.enqueueE, this.finishedE.mapE(function(finished){return NOT_READY;})).collectE([],function(newVal,arr) {
7244         if(newVal==NOT_READY){
7245             return [];
7246         }
7247         arr.push(newVal);
7248         return arr;
7249    });
7250    
7251    var queueE = F.mergeE(this.enqueueE).collectE([],function(newVal,arr) {
7252         arr.push(newVal);
7253         return arr;
7254    });
7255    this.queueB = queueE.startsWith([]);
7256     this.kickstartE = F.liftB(function(queue, finished){
7257         if(!good()){
7258             return NOT_READY;
7259         }
7260         return {queue: queue, finished: finished};
7261     }, this.queueB, finishedB).changes().filterE(function(queueAndFinished){
7262         return queueAndFinished!=NOT_READY && (queueAndFinished.finished && queueAndFinished.queue.length>0);
7263     }).mapE(function(queueAndFinished){
7264         finishedE.sendEvent(false);
7265         startQueueE.sendEvent(true);     
7266     }); 
7267     
7268     var loopedQueueE = startQueueE.snapshotE(this.queueB);
7269     var emptyQueueE = loopedQueueE.filterE(function(queue){return queue!=NOT_READY&&queue.length==0;});
7270     var notEmptyQueueE = loopedQueueE.filterE(function(queue){return queue!=NOT_READY&&queue.length!=0;});
7271     emptyQueueE.mapE(function(){
7272         finishedE.sendEvent(true);
7273     });
7274     notEmptyQueueE.mapE(function(queue){
7275         var val = (collectionType=="stack")?queue.pop():queue.shift();
7276         dequeueEventE.sendEvent(val);
7277     });
7278     this.next = function(){
7279          startQueueE.sendEvent(true);      
7280     };                   
7281 }
7282 
7283 
7284 
7285 
7286 F.EventStream.prototype.ajaxRequestE = function(){
7287     return this.mapE(function(request){
7288     	var timeout = (request.timeout==undefined)?15000:request.timeout;
7289     	var dataType = (request.dataType==undefined)?'text':request.dataType;
7290     	var rec = F.receiverE(); 
7291         jQuery.ajax({				
7292             type: request.type,
7293             data: request.data,
7294             dataType: dataType,
7295             url: request.url,
7296             timeout: timeout,
7297             success: function(data){
7298             	rec.sendEvent(data);
7299             },
7300             error: function(data){log("getAjaxRequestE ERROR on URL: "+request.url);}
7301         });
7302         return rec;
7303     }).switchE();                                          
7304 }
7305 F.EventStream.prototype.ajaxRequestB = function(){
7306     return this.startsWith(NOT_READY).ajaxRequestB();                                          
7307 }
7308 F.Behavior.prototype.ajaxRequestB = function(){
7309     return this.liftB(function(request){
7310     	if(!good()){
7311     		 return NOT_READY;
7312     	}
7313     	var timeout = (request.timeout==undefined)?15000:request.timeout;
7314     	var dataType = (request.dataType==undefined)?'text':request.dataType;
7315     	var rec = F.receiverE(); 
7316         jQuery.ajax({				
7317             type: request.type,
7318             data: request.data,
7319             dataType: dataType,
7320             url: request.url,
7321             timeout: timeout,
7322             success: function(data){
7323             	rec.sendEvent(data);
7324             },
7325             error: function(data){log("getAjaxRequestB ERROR on URL: "+request.url);}
7326         });
7327         return rec.startsWith(NOT_READY);
7328     }).switchB();                                          
7329 }
7330 F.Behavior.prototype.ajaxRequestE = function(){
7331     return this.changes().ajaxRequestE();                                          
7332 }
7333 
7334 F.EventStream.prototype.cancelDOMBubbleE = function(){
7335 	return this.mapE(function(event){DOM.stopEvent(event);return event;});
7336 }
7337 
7338 function showObj(obj){
7339     alert(ObjectToString(obj));
7340 }
7341 function ObjectToString(object){
7342     var output = '';
7343 for (property in object) {
7344   output += property + ': ' + object[property]+'; ';
7345 }                                                   
7346 return output;
7347 }
7348 function countProperties(object){
7349     var count = 0;
7350 for (property in object) {
7351   count++;
7352 }
7353 return count;
7354 }
7355 function printHashTable(table){
7356  var loadWidgets = table.values();
7357     for(i=0;i<table.size();i++){
7358         alert(ObjectToString(loadWidgets[i]));
7359     }
7360 }
7361 
7362 window['log'] = function(message){
7363     if (window.console)
7364         console.log(message);
7365 }
7366 
7367 /*function BehaviourTree(instanceId,data){
7368     var domId=instanceId+"_tree";
7369     var width = (data.placeholder==null)?data.width:data.placeholder.style.width.replace('px', '');
7370     var height = (data.placeholder==null)?data.height:data.placeholder.style.height.replace('px', '');
7371     this.loader=function(){
7372         log("Behaviour Tree loaded");
7373         timerB(1000).liftB(function(){
7374             var container = document.getElementById(domId);
7375             var domDiv = document.createElement("div");
7376             for(index in DATA.localData){
7377                 var behaviour = DATA.localData[index];
7378                 var value = behaviour["_"].last;
7379                 if(value==undefined||value==NOT_READY)
7380                     value = "NOT READY";
7381                 var display = index+": "+value;
7382                 domDiv.appendChild(createDomElement("div", "", "", display));
7383             }  
7384             removeChildren(container);
7385             container.appendChild(domDiv);
7386         });
7387     }
7388     this.destroy=function(){}
7389     this.build=function(){
7390         return "<div class=\"behaviourTree\" style=\"width:"+width+"px; height: "+height+"px\"><div id=\""+domId+"\"></div></div>";
7391     }
7392 }
7393 widgetTypes['BehaviourTree']=BehaviourTree;
7394 
7395 
7396 function BehaviourTest(instanceId,data){
7397     var domId=instanceId+"_tree";
7398     var width = (data.placeholder==null)?data.width:data.placeholder.style.width.replace('px', '');
7399     var height = (data.placeholder==null)?data.height:data.placeholder.style.height.replace('px', '');
7400     this.loader=function(){
7401        var t1B = timerB(500);
7402        var t2B = timerB(350);
7403        
7404        var mergeB = F.liftB(function(t1, t2){
7405         return t1+"<>"+t2;
7406        }, t1B, t2B);
7407        DATA.register("timer1", "", t1B);
7408        DATA.register("timer2", "", t2B);
7409        DATA.register("merge", "", mergeB);
7410        F.insertDomB(mergeB, domId);
7411     }
7412     this.destroy=function(){}
7413     this.build=function(){
7414         return "<div class=\"BehaviourTest\" style=\"width:"+width+"px; height: "+height+"px\"><div id=\""+domId+"\"></div></div>";
7415     }
7416 }
7417 widgetTypes['BehaviourTest']=BehaviourTest;*/
7418 function parseMysqlDate(mysql_string){ 
7419    if(typeof mysql_string === 'string')
7420    {
7421       var t = mysql_string.split(/[- :]/);
7422       return new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);          
7423    }
7424    return null;   
7425 }
7426 function createButton(value, className){
7427     var button = createDomElement("input", undefined,"button");
7428     button.type = "submit";
7429     button.value = value;
7430     if(className!=undefined)
7431         button.className = className;
7432     return button;
7433 }
7434 String.prototype['contains'] = function(str){
7435     return (this.indexOf(str) >= 0);
7436 }
7437 getElementsByClassName = function(class_name, tag, elm) {
7438     doc = elm || this;
7439     var docList = doc.all || doc.getElementsByTagName('*');
7440     var matchArray = new Array();
7441 
7442     /*Create a regular expression object for class*/
7443     var re = new RegExp("(?:^|\\s)"+class_name+"(?:\\s|$)");
7444     for (var i = 0; i < docList.length; i++) {
7445         //showObj(docList[i]);
7446         if (re.test(docList[i].className) ) {
7447             matchArray[matchArray.length] = docList[i];
7448         }
7449     }
7450     return matchArray;
7451 }
7452 Element.prototype.removeChildren = function(element){
7453     if(element==undefined)
7454         element = this;
7455     while (element.hasChildNodes()) {
7456         element.removeChild(element.lastChild);
7457     }
7458 }
7459 function getMilliseconds(){
7460 var d = new Date();
7461 return d.getTime(); 
7462 } 
7463 function createDomElement(type, id, className, innerHTML){
7464     var ele = document.createElement(type);
7465     if(id!=undefined&&id.length>0)
7466     ele.id = id;
7467     if(className!=undefined&&className.length>0)
7468     ele.className = className; 
7469     if(innerHTML!=undefined&&innerHTML.length>0)
7470     ele.innerHTML = innerHTML;
7471     return ele; 
7472 }
7473 function createIcon(src){
7474     var saveButton = document.createElement("img");
7475     saveButton.src=src;
7476     saveButton.style.cursor="pointer";
7477     return saveButton;
7478 }
7479 function findParentNodeWithTag(element, tag){
7480     if(element==undefined||element==null)
7481         return undefined; 
7482     else if(element.tagName.toUpperCase() == tag.toUpperCase())
7483         return element;
7484     return findParentNodeWithTag(element.parentNode, tag);    
7485 }
7486 function findTableRowIndex(table, row){
7487     for(i=0; i<table.rows.length; i++){
7488         if(table.rows[i]==row)
7489             return i;
7490     }
7491     return -1;
7492 }
7493 
7494 function stopEventBubble(event){
7495     agent = jQuery.browser;
7496     if(agent.msie) {
7497         event.cancelBubble = true;
7498     } else {
7499         event.stopPropagation();
7500     }
7501 }
7502 
7503 /* BASE WIDGETS */        
7504 /**
7505  *  WebpageSettingsWidget
7506  * @constructor
7507  */
7508 function VideoPlayerWidget(instanceId, data){
7509     var width = (data.placeholder!=undefined&&data.placeholder.style.width!=undefined)?data.placeholder.style.width:undefined;
7510     var height = (data.placeholder!=undefined&&data.placeholder.style.height!=undefined)?data.placeholder.style.height:undefined;
7511     var poster = (data.poster!=undefined&&data.poster!="")?"&poster="+data.poster+"":"";
7512     var poster2 = (data.poster!=undefined&&data.poster!="")?"<img alt=\"happyfit2\" src=\""+data.poster+"\" style=\"position:absolute;left:0;\" width=\""+width+"\" height=\""+height+"\" title=\"Video playback is not supported by your browser\" />":"";
7513     var poster3 = (data.poster!=undefined&&data.poster!="")?" poster=\""+data.poster+"\"":"";
7514     var sources = data.sources;
7515     var flashPlayer = "/plugins/aurora.media/flashfox.swf";
7516     this.loader=function(){
7517          var sourcesStr = "";
7518         var mp4 = "";
7519         var autoplay = (data.autoplay==true||data.autoplay=="true")?true:false;
7520         for(index in sources){
7521             var type = sources[index]['type'];
7522             //window['SETTINGS']['scriptPath']
7523             if(sources[index]['type']=="video/mp4")
7524                 mp4 = sources[index]['src']; 
7525             sourcesStr += "<source src=\""+sources[index]['src']+"\" type='"+type+"' />";
7526         }
7527         var flashPart = "";
7528         if(mp4!=""){
7529             flashPart = "<object classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" type=\"application/x-shockwave-flash\" data=\""+flashPlayer+"\" width=\"604\" height=\"256\" style=\"position:relative;\">"+
7530                                 "<param name=\"movie\" value=\""+flashPlayer+"\" />"+
7531                                 "<param name=\"allowFullScreen\" value=\"true\" />"+
7532                                 "<param name=\"flashVars\" value=\"autoplay="+autoplay+"&controls=true&loop=true&src="+mp4+"\" />"+
7533                                 "<embed src=\""+flashPlayer+"\" width=\"604\" height=\"256\" flashVars=\"src="+mp4+"&autoplay="+autoplay+"&controls=true&loop=true"+poster+"\"    allowFullScreen=\"true\" wmode=\"transparent\" type=\"application/x-shockwave-flash\" pluginspage=\"http://www.adobe.com/go/getflashplayer_en\" />"+
7534                                 poster2+
7535                                 "</object>";
7536         }
7537         document.getElementById("video").innerHTML = "<video controls=\"controls\" "+(autoplay?" autoplay=\"autoplay\"":"")+"\""+poster3+" width=\""+width+"\" height=\""+height+"\" onclick=\"if(/Android/.test(navigator.userAgent))this.play();\">"+sourcesStr+flashPart+"</video>"; 
7538     }
7539     this.destroy=function(){
7540         DATA.deregister("aurora_settings", "");
7541     }
7542     this.build=function(){     
7543         return "<div id=\"video\"></div>";
7544     }
7545 }   
7546 
7547 function VideoPlayerWidgetConfigurator(){
7548     var id = "VideoWidgetCont";
7549     this['load'] = function(newData){}
7550     this['build'] = function(newData){
7551         var poster = (newData!=undefined&&newData['poster']!=undefined)?newData['poster']:"";
7552         var autoplay = (newData!=undefined&&newData['autoplay']!=undefined)?newData['autoplay']:"false";
7553         var returnString = "";
7554         var src1 = "";
7555         var type1="";
7556         var src2 = "";
7557         var type2="";
7558         var src3 = "";
7559         var type3="";
7560         if(newData!=undefined&&newData['sources'].length>0){
7561             src1 = (newData!=undefined&&newData['sources'][0]['src']!=undefined)?newData['sources'][0]['src']:"";
7562             type1 = (newData!=undefined&&newData['sources'][0]['type']!=undefined)?newData['sources'][0]['type']:""; 
7563              
7564         }
7565         returnString+="SRC: <input type=\"text\" id=\""+id+"_src1\" value=\""+src1+"\" /><br />Type<input type=\"text\" id=\""+id+"_type1\" value=\""+type1+"\" /><br />";
7566         if(newData!=undefined&&newData['sources'].length>1){
7567             src2 = (newData!=undefined&&newData['sources'][1]['src']!=undefined)?newData['sources'][1]['src']:"";
7568             type2 = (newData!=undefined&&newData['sources'][1]['type']!=undefined)?newData['sources'][1]['type']:""; 
7569              
7570         }
7571         returnString+="SRC: <input type=\"text\" id=\""+id+"_src2\" value=\""+src2+"\" /><br />Type<input type=\"text\" id=\""+id+"_type2\" value=\""+type2+"\" /><br />";
7572         if(newData!=undefined&&newData['sources'].length>2){
7573             src3 = (newData!=undefined&&newData['sources'][2]['src']!=undefined)?newData['sources'][2]['src']:"";
7574             type3 = (newData!=undefined&&newData['sources'][2]['type']!=undefined)?newData['sources'][2]['type']:""; 
7575              
7576         }
7577         returnString+="SRC: <input type=\"text\" id=\""+id+"_src3\" value=\""+src3+"\" /><br />Type<input type=\"text\" id=\""+id+"_type3\" value=\""+type3+"\" /><br />";
7578         return returnString+"Poster: <input type=\"text\" id=\""+id+"_poster\" value=\""+poster+"\" /><br />Autoplay: <input type=\"checkbox\" id=\""+id+"_autoplay\"  "+((autoplay)?" checked=\"true\"":"")+" />"; 
7579     }
7580     this['getData'] = function(){
7581         var sources = [];
7582         var src1 = document.getElementById(id+"_src1");
7583         var type1 = document.getElementById(id+"_type1");
7584         var src2 = document.getElementById(id+"_src2");
7585         var type2 = document.getElementById(id+"_type2");
7586         var src3 = document.getElementById(id+"_src3");
7587         var type3 = document.getElementById(id+"_type3");
7588         if(src1.value.length>0){
7589             var type1Value = (type1.value.length==0)?auroraMediaVideoSrcToType(src1):type1.value;
7590             sources.push({"src": src1.value, "type": type1Value});
7591         }
7592         if(src2.value.length>0){
7593             var type2Value = (type2.value.length==0)?auroraMediaVideoSrcToType(src2):type2.value; 
7594             sources.push({"src": src2.value, "type": type2Value});
7595         }
7596         if(src3.value.length>0){
7597             var type3Value = (type3.value.length==0)?auroraMediaVideoSrcToType(src3):type3.value; 
7598             sources.push({"src": src3.value, "type": type3Value});
7599         }
7600         return {"poster": document.getElementById(id+"_poster").value, "autoplay": document.getElementById(id+"_autoplay").checked, "sources": sources};
7601     }
7602     this['getName'] = function(){
7603         return "Video Player Widget";
7604     }
7605     this['getDescription'] = function(){
7606         return "An mp4 player";
7607     }
7608     this['getPackage'] = function(){
7609         return "Audio/Video";
7610     }
7611 } 
7612 WIDGETS.register("VideoPlayerWidget", VideoPlayerWidget, VideoPlayerWidgetConfigurator); 
7613 function BuildProductWidgetHTML(id, title, description, price, text){
7614     var text = (text==undefined)?"Add To Cart":text;
7615     return "<div id=\""+id+"\" class=\"ProductWidget\"><img id=\""+id+"_image\" src=\"resources/aurora.products/"+id+".png\" alt=\"\" class=\"ProductWidgetImg\" /><h2>"+title+"</h2>"+description+"<div style=\"clear:both;\" class=\"ProductWidgetPrice\"><form style=\"float: right;\" target=\"paypal\" action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\"><input id=\""+id+"_submit\" type=\"image\" src=\"/plugins/aurora.products/addtocart.png\" border=\"0\" name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\"><input type=\"hidden\" name=\"cmd\" value=\"_s-xclick\"><input type=\"hidden\" name=\"hosted_button_id\" value=\""+id+"\"></form>$"+price+"</div></div>";
7616 //<input id=\""+id+"_submit\" type=\"submit\" src=\"/border=\"0\" name=\"submit\" value=\""+text+"\" alt=\"PayPal - The safer, easier way to pay online!\">    
7617 //<input id=\""+id+"_submit\" type=\"image\" src=\"/plugins/aurora.products/addtocart.png\" border=\"0\" name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\">    
7618  /*<img alt=\"\" border=\"0\" src=\"https://www.paypalobjects.com/en_US/i/scr/pixel.gif\" width=\"1\" height=\"1\"> */   
7619     
7620 }
7621 /**
7622  *  ProductWidget
7623  * @constructor
7624  */ 
7625 function ProductWidget(instanceId, data){
7626     var id = instanceId+"_container";
7627     var title = data.title;
7628     var description = data.description;
7629     var price = data.price;
7630     var productId = data.productId;
7631     this.loader=function(){
7632         //jQuery("#"+productId+"_submit").button();
7633         var img = document.getElementById(productId+"_image");
7634         if(!img.complete){
7635             img.src = "/resources/trans.png";
7636         }
7637     }
7638     this.destroy=function(){}
7639     this.build=function(){
7640         return BuildProductWidgetHTML(productId, title, description, price);
7641     }                         
7642 }
7643                      
7644 /**
7645  *  UsernameWidgetConfigurator
7646  * @constructor
7647  */                                                      
7648 function ProductWidgetConfigurator(){
7649 	this['load'] = function(newData){}
7650     var id = "ProductWidgetConfigurator";
7651     this['build'] = function(newData){
7652         var productId = "";
7653         var title = ""; 
7654         var description = ""; 
7655         var price = "";
7656         if(newData!=undefined){
7657             productId = newData['productId'];
7658             title = newData['title']; 
7659             description = newData['description']; 
7660             price = newData['price']; 
7661         }
7662         return "Product Id: <input type=\"text\" id=\""+id+"_id\" value=\""+productId+"\" /><br />"+
7663         "Title: <input type=\"text\" id=\""+id+"_title\" value=\""+title+"\" /><br />"+
7664         "Description: <input type=\"text\" id=\""+id+"_description\" value=\""+description+"\" /><br />"+
7665         "Price: <input type=\"text\" id=\""+id+"_price\" value=\""+price+"\" />";
7666     }
7667     this['getData'] = function(){
7668         return {"productId": document.getElementById(id+'_id').value, "title": document.getElementById(id+'_title').value, "description": document.getElementById(id+'_description').value, "price": document.getElementById(id+'_price').value};
7669     }
7670     this['getName'] = function(){
7671         return "Product Widget";
7672     }
7673     this['getDescription'] = function(){
7674         return "A product item with an add to cart button";
7675     }
7676     this['getPackage'] = function(){
7677         return "Products";
7678     }
7679 } 
7680 WIDGETS.register("ProductWidget", ProductWidget, ProductWidgetConfigurator); 
7681 
7682 
7683 
7684 /**
7685  *  ProductWidget
7686  * @constructor
7687  */ 
7688 function ViewCartWidget(instanceId, data){
7689     var id = instanceId+"_container";
7690     
7691     var identifier = (data.code!=undefined)?"<input type=\"hidden\" name=\"encrypted\" value=\""+data.code+"\">":"<input type=\"hidden\" name=\"business\" value=\""+data.business+"\">"
7692     this.loader=function(){}
7693     this.destroy=function(){}
7694     this.build=function(){           //<input type=\"hidden\" name=\"encrypted\" value=\""+code+"\">
7695         return "<form target=\"paypal\" action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\">"+identifier+"<input type=\"hidden\" name=\"cmd\" value=\"_s-xclick\"><input class=\"viewCart\" type=\"image\" src=\"/plugins/aurora.products/cart.png\" border=\"0\" name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\"></form>";
7696     }                         
7697 }
7698 
7699 /*<form target="_self" action="https://www.paypal.com/cgi-bin/webscr"  
7700         method="post">  
7701   
7702     <!-- Identify your business so that you can collect the payments. -->  
7703     <input type="hidden" name="business" value="kin@kinskards.com">  
7704   
7705     <!-- Specify a PayPal Shopping Cart View Cart button. -->  
7706     <input type="hidden" name="cmd" value="_cart">  
7707     <input type="hidden" name="display" value="1">  
7708   
7709     <!-- Display the View Cart button. -->  
7710     <input type="image" name="submit" border="0"  
7711         src="https://www.paypal.com/en_US/i/btn/btn_viewcart_LG.gif"   
7712         alt="PayPal - The safer, easier way to pay online">  
7713     <img alt="" border="0" width="1" height="1"  
7714         src="https://www.paypal.com/en_US/i/scr/pixel.gif" >  
7715 </form> */
7716 
7717                      
7718 /**
7719  *  UsernameWidgetConfigurator
7720  * @constructor
7721  */                                                      
7722 function ViewCartWidgetConfigurator(){
7723 	this['load'] = function(newData){}
7724     var id = "ViewCartWidgetConfigurator";
7725     this['build'] = function(newData){
7726         var code = "";
7727         if(newData!=undefined){
7728             code = newData['code'];
7729         }
7730         return "Product Id: <input type=\"text\" id=\""+id+"_code\" value=\""+code+"\" />";
7731     }
7732     this['getData'] = function(){
7733         return {"code": document.getElementById(id+'_code').value};
7734     }
7735     this['getName'] = function(){
7736         return "Product View Cart Button";
7737     }
7738     this['getDescription'] = function(){
7739         return "A button that takes you to your shopping cart";
7740     }
7741     this['getPackage'] = function(){
7742         return "Products";
7743     }
7744 } 
7745 WIDGETS.register("ViewCartWidget", ViewCartWidget, ViewCartWidgetConfigurator); 
7746 
7747 
7748 
7749 
7750 /*
7751 function VideoPlayerWidget(instanceId, data){
7752     var poster = (data.poster!=undefined&&data.poster!="")?" poster=\""+data.poster+"\"":"";
7753     var width = (data.placeholder!=undefined&&data.placeholder.style.width!=undefined)?data.placeholder.style.width:undefined;
7754     var height = (data.placeholder!=undefined&&data.placeholder.style.height!=undefined)?data.placeholder.style.height:undefined;
7755     var sources = data.sources;
7756     this.loader=function(){                     
7757       
7758     }
7759     this.destroy=function(){
7760         DATA.deregister("aurora_settings", "");
7761     }
7762     this.build=function(){
7763         var sourcesStr = "";
7764         for(index in sources){
7765             sourcesStr += "<source type=\""+sources[index]['type']+"\" src=\""+sources[index]['src']+"\">";
7766         }
7767         //<track kind=\"subtitles\" srclang=\"ru\" src=\"./media/sintel_ru.srt\">
7768         return "<video controls"+poster+" width=\""+width+"\" height=\""+height+"\">"+sourcesStr+"</video>";
7769     }
7770 }     
7771 function VideoPlayerWidgetConfigurator(){
7772 	this['load'] = function(newData){}
7773     var id = "VideoWidgetCont";
7774     this['build'] = function(newData){
7775         var poster = (newData!=undefined&&newData['poster']!=undefined)?newData['poster']:"";
7776         var returnString = "";
7777         var src1 = "";
7778         var type1="";
7779         var src2 = "";
7780         var type2="";
7781         var src3 = "";
7782         var type3="";
7783         
7784         if(newData!=undefined&&newData['sources'].length>0){
7785             src1 = (newData!=undefined&&newData['sources'][0]['src']!=undefined)?newData['sources'][0]['src']:"";
7786             type1 = (newData!=undefined&&newData['sources'][0]['type']!=undefined)?newData['sources'][0]['type']:""; 
7787              
7788         }
7789         returnString+="SRC: <input type=\"text\" id=\""+id+"_src1\" value=\""+src1+"\" /><br />Type<input type=\"text\" id=\""+id+"_type1\" value=\""+type1+"\" /><br />";
7790         if(newData!=undefined&&newData['sources'].length>1){
7791             src2 = (newData!=undefined&&newData['sources'][1]['src']!=undefined)?newData['sources'][1]['src']:"";
7792             type2 = (newData!=undefined&&newData['sources'][1]['type']!=undefined)?newData['sources'][1]['type']:""; 
7793              
7794         }
7795         returnString+="SRC: <input type=\"text\" id=\""+id+"_src2\" value=\""+src2+"\" /><br />Type<input type=\"text\" id=\""+id+"_type2\" value=\""+type2+"\" /><br />";
7796         if(newData!=undefined&&newData['sources'].length>2){
7797             src3 = (newData!=undefined&&newData['sources'][2]['src']!=undefined)?newData['sources'][2]['src']:"";
7798             type3 = (newData!=undefined&&newData['sources'][2]['type']!=undefined)?newData['sources'][2]['type']:""; 
7799              
7800         }
7801         returnString+="SRC: <input type=\"text\" id=\""+id+"_src3\" value=\""+src3+"\" /><br />Type<input type=\"text\" id=\""+id+"_type3\" value=\""+type3+"\" /><br />";
7802         return returnString+"Poster: <input type=\"text\" id=\""+id+"_poster\" value=\""+poster+"\" />"; 
7803     }
7804     this['getData'] = function(){
7805         var sources = [];
7806         var src1 = document.getElementById(id+"_src1");
7807         var type1 = document.getElementById(id+"_type1");
7808         var src2 = document.getElementById(id+"_src2");
7809         var type2 = document.getElementById(id+"_type2");
7810         var src3 = document.getElementById(id+"_src3");
7811         var type3 = document.getElementById(id+"_type3");
7812         if(src1.value.length>0){
7813             var type1Value = (type1.value.length==0)?auroraMediaVideoSrcToType(src1):type1.value;
7814             sources.push({"src": src1.value, "type": type1Value});
7815         }
7816         if(src2.value.length>0){
7817             var type2Value = (type2.value.length==0)?auroraMediaVideoSrcToType(src2):type2.value; 
7818             sources.push({"src": src2.value, "type": type2Value});
7819         }
7820         if(src3.value.length>0){
7821             var type3Value = (type3.value.length==0)?auroraMediaVideoSrcToType(src3):type3.value; 
7822             sources.push({"src": src3.value, "type": type3Value});
7823         }
7824         return {"poster": document.getElementById(id+"_poster").value, "sources": sources};
7825     }
7826     this['getName'] = function(){
7827         return "Video Player Widget";
7828     }
7829     this['getDescription'] = function(){
7830         return "An mp4 player";
7831     }
7832     this['getPackage'] = function(){
7833         return "Audio/Video";
7834     }
7835 } */
7836 var tableBackgroundColor = "#FFFFFF";
7837 var tableBackgroundColorSelected = "#b3ddf8";
7838 var CELL_RENDERERS = {"boolean":BooleanCellRenderer, "string":StringCellRenderer, "int":IntegerCellRenderer,"float":StringCellRenderer, "gender":GenderColumn, "date":(typeof(jQuery)=='undefined')?StringCellRenderer:DateColumn, "RW": ReadWriteColumn, "readWrite": ReadWriteColumn};
7839                                                                                      
7840                                     
7841 
7842 
7843 function cleanFunctions(obj) {
7844     if(jQuery.isArray(obj)||jQuery.type(obj) === "object"){
7845         for (var name in obj){
7846             obj[name] = cleanFunctions(obj[name]);
7847         }
7848     }
7849     else if(jQuery.isFunction(obj)){
7850         return undefined;   
7851     }
7852     return obj;
7853 }
7854 
7855 function cleanRenderers(table){
7856     for(colIndex in table["COLUMNMETADATA"]){
7857         table["COLUMNMETADATA"][colIndex]["renderer"] = undefined;    
7858     }
7859     for(rowIndex in table["ROWMETADATA"]){
7860         table["ROWMETADATA"][rowIndex]["renderer"] = undefined;    
7861     }
7862     for(rowIndex in table["CELLMETADATA"]){
7863         var row = table["CELLMETADATA"][rowIndex];
7864         if(row!=undefined){
7865             for(colIndex in row){
7866                 var cell = row[colIndex];
7867                 cell["renderer"] = undefined; 
7868             }
7869         }    
7870     }
7871     return table;
7872 }
7873 
7874 /**
7875  *  BasicSelectCellRenderer
7876  * @constructor
7877  */
7878 function BasicSelectCellRenderer(options, value, cell, width){
7879     var element = document.createElement("select");
7880     var selectedElement = 0;
7881     for(optionIndex in options){
7882         var option = options[optionIndex];
7883         var optionElement = document.createElement("option");
7884         optionElement.value = option.value;
7885         optionElement.innerHTML = option.display;
7886         element.appendChild(optionElement);
7887         if(optionElement.value==value)
7888             selectedElement = optionIndex;
7889     }    
7890     element.selectedIndex = selectedElement;
7891     cell.appendChild(element);
7892     
7893     this.render = function(){
7894         element.disabled = true;
7895     }
7896     this.getValue = function(){
7897         return element.value;
7898     }
7899     this.renderEditor = function(){
7900         element.disabled = false;   
7901     }
7902     this.setSelected = function(selected){ 
7903         if(selected){
7904             cell.className="TableWidgetCellSelected"; 
7905            // cell.style.backgroundColor=tableBackgroundColorSelected; 
7906         }                                  
7907         else{
7908             cell.className="TableWidgetCell"; 
7909             //cell.style.backgroundColor=tableBackgroundColor; 
7910         }
7911     }
7912     this.setValue = function(newValue){
7913         element.value = newValue;
7914     }
7915     this.getUpdateEvent = function(){
7916         return F.extractValueE(element);
7917     }
7918 }
7919 /**
7920  *  BasicSelectCellRendererContainer
7921  * @constructor
7922  */
7923 function BasicSelectCellRendererContainer(options){       
7924     this.getCellRenderer = function(value, cell, width){
7925         return new BasicSelectCellRenderer(options, value, cell, width);
7926     }
7927 }
7928 //table
7929 /**
7930  *  BasicRadioCellRenderer
7931  * @constructor
7932  */
7933 function BasicRadioCellRenderer(name, options, value, cell, width){
7934     this.elements = [];
7935     this.events = new Array();
7936     for(optionIndex in options){
7937         var div = document.createElement("div");
7938         div.style.textAlign = "center";
7939         var option = options[optionIndex];
7940         var element = document.createElement("input");
7941         element.type = "radio";
7942         element.name = name;
7943         element.value = option.value;
7944         div.appendChild(document.createTextNode(option.display));
7945         div.appendChild(element);
7946         cell.appendChild(div);
7947         this.elements.push(element);
7948         if(element.value == value)
7949             element.checked = true;
7950         var event = F.extractEventE(element, "change");
7951         this.events.push(event);
7952     }
7953     this.valueChangeEventE = F.mergeE.apply(this, this.events);  
7954     this.render = function(){
7955         this.enabled(false);
7956     }
7957     this.enabled = function(en){
7958         for(elementIndex in this.elements){
7959             var element = this.elements[elementIndex];
7960             element.disabled = !en;
7961         }
7962     }
7963     this.getValue = function(){
7964         for(elementIndex in this.elements){
7965             var element = this.elements[elementIndex];
7966             if(element.checked==true){
7967                 return element.value;
7968             }
7969         }
7970         return "";
7971     }
7972     this.renderEditor = function(){
7973         this.enabled(true);
7974     }
7975     this.setSelected = function(selected){ 
7976         if(selected){
7977             cell.className="TableWidgetCellSelected"; 
7978            // cell.style.backgroundColor=tableBackgroundColorSelected; 
7979         }                                  
7980         else{
7981             cell.className="TableWidgetCell"; 
7982             //cell.style.backgroundColor=tableBackgroundColor; 
7983         }
7984     }
7985     this.setValue = function(newValue){
7986         for(elementIndex in this.elements){
7987             var element = this.elements[elementIndex];
7988             if(element.value==newValue){
7989                element.checked = true
7990             }
7991             else
7992                 element.checked = false;
7993         }
7994     }
7995     this.getUpdateEvent = function(){
7996         return this.valueChangeEventE;
7997     }
7998 }
7999 /**
8000  *  BasicRadioCellRendererContainer
8001  * @constructor
8002  */
8003 function BasicRadioCellRendererContainer(name, options){
8004     this.getCellRenderer = function(value, cell, width){
8005         return new BasicRadioCellRenderer(name, options, value, cell, width);
8006     }
8007 }
8008 /**
8009  *  BasicCellRenderer
8010  * @constructor
8011  */
8012 function BasicCellRenderer(type, name){ 
8013     this.getCellRenderer = function(value, cell, width){
8014         var renderClass = CELL_RENDERERS[type];
8015         var renderer = new renderClass(value, cell, width);
8016         //log(renderer);
8017         return renderer; 
8018     }
8019 }
8020 /**
8021  *  DefaultCellRenderer
8022  * @constructor
8023  */
8024 function DefaultCellRenderer(value, cell, width){
8025     this.render = function(){
8026         cell.innerHTML = value;
8027     }
8028     this.getValue = function(){
8029         return cell.innerHTML;
8030     }
8031     this.renderEditor = function(){
8032         
8033     }
8034     this.setSelected = function(selected){ 
8035         if(selected){
8036             cell.className="TableWidgetCellSelected"; 
8037            // cell.style.backgroundColor=tableBackgroundColorSelected; 
8038         }                                  
8039         else{
8040             cell.className="TableWidgetCell"; 
8041             //cell.style.backgroundColor=tableBackgroundColor; 
8042         }
8043     }
8044     this.setValue = function(newValue){
8045         value = newValue;
8046     }
8047     this.getUpdateEvent = function(){
8048         return F.receiverE();
8049     }
8050 }
8051 /**
8052  *  BooleanCellRenderer
8053  * @constructor
8054  */
8055 function BooleanCellRenderer(value, cell, width){    
8056     var value = (value!=undefined&&(value=="1"||value==true||value=="true"))?true:false;
8057     var checkbox = document.createElement("input");
8058     checkbox.type='checkbox';
8059     checkbox.checked = value;  
8060     cell.className="TableWidgetBooleanCell";
8061     checkbox.disabled = true; 
8062     
8063     this.render = function(){
8064         cell.removeChildren();
8065         checkbox.disabled = true; 
8066         cell.appendChild(checkbox);
8067         //jQuery(cell).fj('extEvtE', 'click').mapE(function(x){userChangeE.sendEvent()});
8068     }
8069     this.renderEditor = function(){
8070         cell.removeChildren();
8071         checkbox.disabled = false;
8072         cell.appendChild(checkbox);
8073     }
8074     this.setSelected = function(selected){
8075         //log("Chaning boolean "+selected);
8076         if(selected){
8077             cell.className="TableWidgetBooleanCellSelected";
8078             //cell.style.backgroundColor=tableBackgroundColorSelected;  
8079         }
8080         else  {
8081             cell.className="TableWidgetBooleanCell"; 
8082             //cell.style.backgroundColor=tableBackgroundColorSelected; 
8083         }
8084     }
8085     this.getValue = function(){
8086         return checkbox.checked;
8087     }
8088     this.setValue = function(newValue){
8089         checkbox.checked = newValue;
8090     }
8091     this.getUpdateEvent = function(){
8092         return F.extractValueE(checkbox);
8093     }
8094 }
8095 /**
8096  *  ReadWriteColumn
8097  * @constructor
8098  */
8099 function ReadWriteColumn(value, cell, width){
8100     value = (value==undefined||value==null||value=="")?"":value;
8101     var select = document.createElement("select");
8102     
8103 noneOption=document.createElement("OPTION");
8104     noneOption.appendChild(document.createTextNode("--"));
8105     noneOption.value = "";
8106     select.appendChild(noneOption)
8107 
8108 readOption=document.createElement("OPTION");
8109     readOption.appendChild(document.createTextNode("Read"));
8110     readOption.value = "R";
8111     select.appendChild(readOption);
8112 
8113     writeOption=document.createElement("OPTION");
8114     writeOption.appendChild(document.createTextNode("Write"));
8115     writeOption.value = "W";
8116     select.appendChild(writeOption)
8117 
8118 rwOption=document.createElement("OPTION");
8119     rwOption.appendChild(document.createTextNode("Read+Write"));
8120     rwOption.value = "RW";
8121     select.appendChild(rwOption); 
8122     select.className="TableWidgetPermissionsCell";
8123     select.value = value;
8124      cell.className="TableWidgetCell"; 
8125            
8126     this.render = function(){
8127         cell.removeChildren();
8128         select.disabled = true; 
8129         cell.appendChild(select);
8130     }
8131     this.renderEditor = function(){
8132         cell.removeChildren();
8133         cell.appendChild(select);
8134         select.disabled = false;            
8135     }
8136     this.setSelected = function(selected){
8137         if(selected){
8138             cell.className="TableWidgetCellSelected"; 
8139             //cell.style.backgroundColor=tableBackgroundColorSelected; 
8140         }
8141         else                                                         {
8142             cell.className="TableWidgetCell"; 
8143             //cell.style.backgroundColor=tableBackgroundColor; 
8144         }
8145     }
8146     this.getValue = function(){
8147         return select.value;
8148     }
8149     this.setValue = function(newValue){
8150         select.value = newValue;
8151     }
8152     this.getUpdateEvent = function(){
8153         return F.extractValueE(select);
8154     }
8155 }
8156 /**
8157  *  GenderColumn
8158  * @constructor
8159  */
8160 function GenderColumn(value, cell, width){
8161     value = (value==undefined||value==null||value=="")?"M":value;
8162     var select = document.createElement("select");
8163     maleOption=document.createElement("OPTION");
8164     maleOption.appendChild(document.createTextNode("Male"));
8165     maleOption.value = "M";
8166     femaleOption=document.createElement("OPTION");
8167     femaleOption.appendChild(document.createTextNode("Female"));
8168     femaleOption.value = "F";
8169     select.appendChild(maleOption);
8170     select.appendChild(femaleOption); 
8171     select.className="TableWidgetGenderCell";
8172     select.value = value;
8173      cell.className="TableWidgetCell"; 
8174            
8175     this.render = function(){
8176         cell.removeChildren();
8177         select.disabled = true; 
8178         cell.appendChild(select);
8179     }
8180     this.renderEditor = function(){
8181         cell.removeChildren();
8182         cell.appendChild(select);
8183         select.disabled = false;            
8184     }
8185     this.setSelected = function(selected){
8186         if(selected){
8187             cell.className="TableWidgetCellSelected"; 
8188             //cell.style.backgroundColor=tableBackgroundColorSelected; 
8189         }
8190         else                                                         {
8191             cell.className="TableWidgetCell"; 
8192             //cell.style.backgroundColor=tableBackgroundColor; 
8193         }
8194     }
8195     this.getValue = function(){
8196         return select.value;
8197     }
8198     this.setValue = function(newValue){
8199         select.value = newValue;
8200     }
8201     this.getUpdateEvent = function(){
8202         return F.extractValueE(select);
8203     }
8204 }
8205 /**
8206  *  DateColumn
8207  * @constructor
8208  */
8209 function DateColumn(value, cell, width){
8210    value = (value==undefined||value==null||value=="")?"2012-01-01":value;
8211     var div = document.createElement("div");
8212     cell.className="TableWidgetCell"; 
8213            
8214     var input = document.createElement("input");
8215     input.type = "text";
8216     //input.className = "TableWidgetStringCellRenderTextBox";
8217     this.render = function(){
8218         jQuery(input).datepicker("destroy");
8219         div.innerHTML = value;
8220         //jQuery(input).datepicker("setDate", value); 
8221         cell.removeChildren(); 
8222         cell.appendChild(div);
8223         
8224     }
8225     this.renderEditor = function(){     
8226         cell.removeChildren(); 
8227         cell.appendChild(input);
8228         //input.className = "TableWidgetStringCellTextBox";
8229         input.value = value;
8230         jQuery(input).datepicker({ dateFormat: 'yy-mm-dd', changeMonth: false,changeYear: true, yearRange: '1910:2100', showButtonPanel: false});
8231         jQuery(input).datepicker("setDate", value); 
8232         //jQuery(input).datepicker("show");           
8233     }
8234     this.setSelected = function(selected){
8235         if(selected){
8236             cell.className="TableWidgetCellSelected"; 
8237             //cell.style.backgroundColor=tableBackgroundColorSelected; 
8238         }
8239         else                                                         {
8240             cell.className="TableWidgetCell"; 
8241            // cell.style.backgroundColor=tableBackgroundColor; 
8242         }
8243     }
8244     this.getValue = function(){
8245         date = jQuery.datepicker.formatDate('yy-mm-dd',jQuery(input).datepicker("getDate"));
8246         //date = jQuery(input).datepicker("getDate");
8247         return date;
8248     }
8249     this.setValue = function(newValue){
8250         jQuery(input).datepicker("setDate", newValue);
8251     }
8252     this.getUpdateEvent = function(){
8253         return jQuery(input).datepicker().fj('jQueryBind', 'change');
8254     }
8255 }        
8256 /**
8257  *  StringCellRenderer
8258  * @constructor
8259  */
8260 function StringCellRenderer(value, cell, width){
8261     value = (value==undefined||value==null)?"":value;
8262     var displayDom = document.createElement("div");
8263     displayDom.className = "TableWidgetStringCellText";
8264     cell.className="TableWidgetStringCell";
8265     var textbox = document.createElement("input");
8266     textbox.className = "TableWidgetStringCellTextBox";
8267     textbox.type='text';
8268     textbox.value = value;
8269     //textbox.disabled = true;                 
8270     this.render = function(){ 
8271             displayDom.innerHTML = textbox.value; 
8272             cell.removeChildren(); 
8273             cell.appendChild(displayDom);
8274     }
8275     this.renderEditor = function(){
8276             var scrollWidth = (cell.scrollWidth==0)?cell.style.width:cell.scrollWidth+"px";
8277             if(width!=undefined){
8278                 textbox.style.width = width+"px";
8279             }    
8280             cell.removeChildren();
8281             cell.appendChild(textbox);
8282     }                                         
8283     this.setSelected = function(selected){
8284         
8285         if(selected){
8286             cell.className="TableWidgetStringCellSelected"; 
8287             //cell.style.backgroundColor=tableBackgroundColorSelected;
8288         }
8289         else{
8290             cell.className="TableWidgetStringCell"; 
8291             ///cell.style.backgroundColor=tableBackgroundColor;
8292         }
8293     }
8294     this.getValue = function(){
8295         return textbox.value;
8296     }
8297     this.setValue = function(newValue){
8298         textbox.value = newValue;
8299     }
8300     this.getUpdateEvent = function(){
8301         return F.extractValueE(textbox);
8302     }
8303 }
8304 /**
8305  *  IntegerCellRenderer
8306  * @constructor
8307  */
8308 function IntegerCellRenderer(value, cell, width){
8309     value = (value==undefined||value==null)?"":value;
8310     var displayDom = document.createElement("div");
8311     displayDom.className = "TableWidgetStringCellText";     //TableWidgetIntegerCellText
8312     cell.className="TableWidgetStringCell";
8313     var textbox = document.createElement("input");
8314 //    textbox.className = "TableWidgetStringCellTextBox";       //TableWidgetIntegerCellTextBox
8315     textbox.type='text';
8316     textbox.value = value;
8317     //textbox.disabled = true;                 
8318     this.render = function(){ 
8319             displayDom.innerHTML = textbox.value; 
8320             cell.removeChildren(); 
8321             cell.appendChild(displayDom);
8322     }
8323     this.renderEditor = function(){
8324             var scrollWidth = (cell.scrollWidth==0)?cell.style.width:cell.scrollWidth+"px";
8325             if(width!=undefined){
8326                 textbox.style.width = width+"px";
8327             }    
8328             cell.removeChildren();
8329             cell.appendChild(textbox);
8330     }                                         
8331     this.setSelected = function(selected){
8332         
8333         if(selected){
8334             cell.className="TableWidgetStringCellSelected"; 
8335             //cell.style.backgroundColor=tableBackgroundColorSelected;
8336         }
8337         else{
8338             cell.className="TableWidgetStringCell"; 
8339             ///cell.style.backgroundColor=tableBackgroundColor;
8340         }
8341     }
8342     this.getValue = function(){
8343         var val = textbox.value;
8344         if(val.length==0)
8345             val = 0;
8346         return parseFloat(val);
8347     }
8348     this.setValue = function(newValue){
8349         textbox.value = newValue;
8350     }
8351     this.getUpdateEvent = function(){
8352         return F.extractValueE(textbox);
8353     }
8354 }
8355 
8356 /**                            
8357  *  TableWidgetB
8358  * @constructor
8359  */
8360 function TableWidgetB(instanceId, widgetData, dataB){
8361     if(arguments.length!=3)
8362         log("Error TableWidgetB called with wrong argument count");
8363     var table = document.createElement("table");
8364     table.id = instanceId+"_table";
8365     table.className = "TableWidget";
8366     this.table = table;
8367     var confirmChanges = (widgetData!=undefined&&widgetData.confirmChanges!=undefined)?widgetData.confirmChanges:true;
8368     var confirmChangesB = F.constantB(confirmChanges);
8369    //Control Bar Buttons
8370     var saveButton = createIcon(window['SETTINGS']['theme'].path+"save.png");
8371     var cancelButton = createIcon(window['SETTINGS']['theme'].path+"cancel.png");
8372     var addRowButton = createIcon(window['SETTINGS']['theme'].path+"add.png");
8373     var deleteRowButton = createIcon(window['SETTINGS']['theme'].path+"delete.png"); 
8374     
8375     var addRow = document.createElement("tr");
8376     var controlsRow = document.createElement("tr");
8377     var controlsCell = document.createElement("td");
8378             
8379             controlsCell.className = "TableWidgetControlBar";
8380             controlsCell.appendChild(saveButton);
8381             controlsCell.appendChild(cancelButton); 
8382             controlsCell.appendChild(addRowButton);
8383             controlsCell.appendChild(deleteRowButton);
8384             controlsRow.appendChild(controlsCell);
8385     
8386     var width = (widgetData.placeholder!=undefined&&widgetData.placeholder.style.width!=undefined)?widgetData.placeholder.style.width:undefined;
8387     var height = (widgetData.placeholder!=undefined&&widgetData.placeholder.style.height!=undefined)?widgetData.placeholder.style.height:undefined;
8388     var containerId = instanceId+"_cont";
8389     
8390     //Build Heading Row
8391     //Events
8392     var userEventE = F.receiverE();
8393     var userEventB = userEventE.startsWith("view");
8394     
8395     var triggerSaveE = F.receiverE();
8396     var saveButtonPressedE = F.mergeE(triggerSaveE, F.extractEventE(saveButton,'click'));
8397     var cancelButtonPressedE = F.extractEventE(cancelButton,'click');   
8398     var addButtonPressedE = F.extractEventE(addRowButton,'click');
8399    var deleteButtonPressedE = F.extractEventE(deleteRowButton,'click');
8400     
8401     var sortingDOMColumnE = F.receiverE();
8402     var sortingDOMColumnB = sortingDOMColumnE.startsWith(NOT_READY);
8403     
8404     var sortedTableB = F.liftBI(function(sortingDOMColumn, table){
8405         //log("sortedTableB");
8406         if(table==NOT_READY){
8407             return NOT_READY;
8408         }
8409         if(sortingDOMColumn!=NOT_READY){
8410             var columns = table["COLUMNS"];
8411             var count = 0;
8412             for(index in columns){
8413                 if(count==sortingDOMColumn&&columns[index]['visible']){
8414                     if(table['TABLEMETADATA']['sortColumn']==index){
8415                         table['TABLEMETADATA']['sortOrder'] = (table['TABLEMETADATA']['sortOrder']=="ASC")?"DESC":"ASC";    
8416                     }
8417                     table['TABLEMETADATA']['sortColumn'] = index;
8418                 }
8419                 if(columns[index]['visible']){
8420                     count++;
8421                 }               
8422             }
8423         }
8424         
8425         return table;
8426     },function(value){
8427         return [NOT_READY, value];
8428     }, sortingDOMColumnB, dataB);
8429     
8430     //extractEventE(table,"click")                   jQuery(table).fj('extEvtE', 'click')
8431     var tableRowClickedE = F.extractEventE(table,"click").mapE(function(ev){
8432         stopEventBubble(ev);
8433         //ev.preventDefault();
8434         //return NOT_READY;
8435        // log("Row clicked");
8436         var target = (ev.target==undefined)?ev.srcElement:ev.target;
8437         jQuery(target).focus();
8438         if(target.tagName=="TH"){
8439             sortingDOMColumnE.sendEvent(jQuery(target).parent().children().index(target));  
8440             return NOT_READY;
8441         }
8442         var cell = findParentNodeWithTag(target, "td");
8443         var row = findParentNodeWithTag(cell, "tr");
8444         var table =findParentNodeWithTag(row, "table");
8445             if(row!=undefined){
8446                 var clickedIndex = jQuery(row).prevAll().length;
8447                 if(clickedIndex<=0 || (table.rows.length-1)==clickedIndex){
8448                     return NOT_READY;
8449                 }
8450                 return {clickedIndex: clickedIndex, shiftKey: ev.shiftKey, ctrlKey: ev.ctrlKey, target: target};
8451             }
8452         return NOT_READY;
8453     }).filterE(function(v){return v!=NOT_READY;});
8454     
8455     var tableBlurE = jQuery(document).fj('extEvtE', 'click').mapE(function(x){return NOT_READY;});    
8456     var rowSelectionResetE = F.receiverE();
8457     var tableSelectionRowIndexE = F.mergeE(tableRowClickedE, rowSelectionResetE.mapE(function(v){return NOT_READY;}), tableBlurE);
8458     var rowSelectionsE = tableSelectionRowIndexE.collectE([],function(newElement,arr) {
8459         if(newElement==NOT_READY)
8460             return []; 
8461            // log("Col");
8462         var clickedIndex = newElement.clickedIndex;
8463         var shiftKey = newElement.shiftKey;
8464         var ctrlKey = newElement.ctrlKey;
8465         if(ctrlKey){        
8466             if(arrayContains(arr, clickedIndex)){
8467                 arr = jQuery.grep(arr, function(value) {return value != clickedIndex;});
8468             }
8469             else {
8470                 arr[arr.length] = clickedIndex;
8471             }
8472         }
8473         else if(shiftKey){
8474             var min = Array.max(arr);
8475             var max = Array.min(arr);
8476             if(clickedIndex<min){
8477                 for(i=clickedIndex;i<min;i++)
8478                     arr[arr.length] = i;    
8479             }
8480             else if(clickedIndex>max){
8481                 for(i=max+1;i<=clickedIndex;i++)
8482                     arr[arr.length] = i; 
8483             }
8484         }
8485         else{
8486             if(arr.length==1&&arrayContains(arr, clickedIndex)){
8487                 arr = [];
8488             }
8489             else{
8490                 arr = [clickedIndex];
8491             }
8492         }
8493         
8494            
8495         return arr;
8496     });
8497     var rowSelectionsB = rowSelectionsE.startsWith([]);
8498     
8499     
8500     
8501     
8502     
8503     var showAddRowsResetE = F.receiverE();
8504     
8505     var showAddRowsB = F.mergeE(addButtonPressedE, showAddRowsResetE).collectE(false,function(newVal,lastVal){if(newVal==NOT_READY)return false;return !lastVal; }).startsWith(false);
8506            
8507     
8508     var pageRenderedB = F.liftBI(function(tableData){
8509         //log("pageRenderedB");
8510         table.removeChildren();
8511         addRow.removeChildren();
8512         //If not ready, show a loading icon
8513         if(tableData==NOT_READY){
8514             var element = document.createElement("td");
8515             element.className = "TableWidgetCell";
8516             jQuery(element).attr('colspan',visibleColumnCount);                                         
8517             element.style.textAlign="center";
8518             element.innerHTML = "<img src=\""+window['SETTINGS']['theme'].path+"loading.gif\" alt=\"\"/>";
8519             table.appendChild(element);
8520             return [new Array(), table, new Array(), document.createElement("div"), F.zeroE()];
8521         }  
8522         else if(tableData==NO_PERMISSION){
8523             var element = document.createElement("td");
8524             element.className = "TableWidgetCell";
8525             jQuery(element).attr('colspan',visibleColumnCount);                                         
8526             element.style.textAlign="center";
8527             element.innerHTML = "<img src=\""+window['SETTINGS']['theme'].path+"noperm.png\" alt=\"\"/><br />No Permission";
8528             table.appendChild(element);
8529             return [new Array(), table, new Array(), document.createElement("div"), F.zeroE()];
8530         }  
8531         //log(tableData);
8532         var headingTableRow = document.createElement("tr");
8533         var visibleColumnCount = 0;
8534        /* if(tableData['COLUMNS']==undefined){
8535             for (property in tableData){
8536                 alert(property);
8537             }
8538             return;
8539         }  */
8540         
8541         
8542         var columns = tableData['COLUMNS'];
8543         var columnClicks = [];
8544         jQuery(controlsCell).attr('colspan',columns.length); 
8545         for(index in columns){ 
8546             var col = columns[index];
8547             //log(col);
8548             if(col.visible){
8549                 var cell = document.createElement("th");
8550                 if(col.width!=undefined){
8551                     cell.width = col.width;
8552                 }
8553                 cell.innerHTML = col.display;
8554                 headingTableRow.appendChild(cell);
8555                 visibleColumnCount++;
8556                 columnClicks.push(F.extractEventE(cell, 'click'));
8557             }
8558         }
8559         var columnClicksE = F.mergeE.apply(this, columnClicks);
8560         table.appendChild(headingTableRow);
8561         
8562         
8563         //If ready render the table
8564         var tableMetaData = tableData['TABLEMETADATA'];
8565         var tablePermissions = (tableMetaData!=undefined&&tableMetaData['permissions']!=undefined&&tableMetaData['permissions']['canEdit']!=undefined)?tableMetaData['permissions']['canEdit']:true; 
8566       //  log("SortColumn: "+tableMetaData['sortColumn']);
8567         if(tableMetaData!=undefined&&tableMetaData['sortColumn']!=undefined){
8568             var sortCol = tableMetaData['sortColumn'];
8569         //    log(sortCol);
8570             if(sortCol!=undefined){
8571               //  log("INIF");
8572                 var sortOrder = (tableMetaData['sortOrder']==undefined)?"DESC":tableMetaData['sortOrder'];
8573                // log(sortOrder);
8574                 tableData['DATA'].sort(((tableData['COLUMNMETADATA'][sortCol]!=undefined&&tableData['COLUMNMETADATA'][sortCol]['sorter']!=undefined)?tableData['COLUMNMETADATA'][sortCol]['sorter']:function(row1, row2){return (typeof row1[sortCol] === 'string')?row1[sortCol].localeCompare( row2[sortCol]):row1[sortCol] - row2[sortCol];}));    
8575                 if(sortOrder=="ASC"){
8576                     tableData['DATA'].reverse();
8577                 }
8578                 //return row1[filenameIndex].localeCompare(row2[filenameIndex]); 
8579             }
8580         } 
8581         
8582         var data = tableData['DATA'];
8583         renderedTable = new Array(); 
8584         for(index in data){
8585             var domRow = document.createElement("tr");
8586             var dataRow = data[index];
8587             var rowMetaData = tableData['ROWMETADATA'][index];
8588             var rowPermissions = (rowMetaData!=undefined&&rowMetaData['permissions']!=undefined)?rowMetaData['permissions']:"RW";
8589             if(renderedTable[index]==undefined)
8590                 renderedTable[index] = new Array();
8591             for(cellIndex in columns){
8592                 var columnMetaData = tableData['COLUMNMETADATA'][cellIndex];
8593                 var columnPermissions = columnMetaData==undefined||columnMetaData['permissions']==undefined?"RW":columnMetaData['permissions'];
8594                 var cellMetaData = (tableData['CELLMETADATA']==undefined||tableData['CELLMETADATA'][index]==undefined)?undefined:tableData['CELLMETADATA'][index][cellIndex];
8595                 var cellPermissions = cellMetaData==undefined||cellMetaData['permissions']==undefined?"RW":cellMetaData['permissions']; 
8596                 var rowNumber = parseInt(cellIndex)+1;
8597                 var cell = document.createElement("td");
8598                 var column = columns[cellIndex];
8599 		var customRenderer = (rowMetaData!=undefined&&rowMetaData["renderer"]!=undefined)?rowMetaData["renderer"]:(columnMetaData!=undefined&&columnMetaData["renderer"]!=undefined)?columnMetaData["renderer"]:(cellMetaData!=undefined&&cellMetaData["renderer"]!=undefined)?cellMetaData["renderer"]:undefined;
8600 
8601                 if(customRenderer==undefined){
8602                     var renderClass = (CELL_RENDERERS[column.type]==undefined)?DefaultCellRenderer:CELL_RENDERERS[column.type];
8603                     var renderer = new renderClass(dataRow[cellIndex], cell, column.width);
8604                 }
8605                 else{
8606                     var renderer = customRenderer.getCellRenderer(dataRow[cellIndex], cell, column.width); 
8607                 } 
8608                 
8609 		if(tablePermissions==true&&rowPermissions=="RW"&&columnPermissions=="RW"&&cellPermissions=="RW")
8610                     renderer.renderEditor();    
8611                 else
8612                     renderer.render();
8613                 if(renderedTable[index]==undefined)
8614                     renderedTable[index] = new Array();
8615                 
8616                 renderedTable[index][cellIndex] = {"renderer":renderer, "column":column,"domCell":cell,"domRow":domRow,"validator":null,"rowIndex":index,"colIndex":cellIndex};          
8617                 if(column.visible){                                
8618                     domRow.appendChild(cell);
8619                 }
8620             }                                                                                           
8621             table.appendChild(domRow);    
8622         }
8623             
8624             newRowsRenderedTable = new Array();
8625             for(cellIndex in columns){
8626                 var columnMetaData = tableData['COLUMNMETADATA'][cellIndex];
8627                 var columnPermissions = columnMetaData==undefined?"RW":columnMetaData.permissions;
8628                 
8629                 var rowNumber = parseInt(cellIndex)+1;
8630                 var cell = document.createElement("td");
8631                 var column = columns[cellIndex];
8632                 var customRenderer = (columnMetaData!=undefined&&columnMetaData["renderer"]!=undefined)?columnMetaData["renderer"]:undefined;	
8633 		if(customRenderer==undefined){                           
8634 			var renderClass = (CELL_RENDERERS[column.type]!=undefined)?CELL_RENDERERS[column.type]:DefaultCellRenderer;
8635                     	renderer = new renderClass(undefined, cell, column.width);
8636                 }
8637                 else{                   
8638 			renderer = customRenderer.getCellRenderer(undefined, cell, column.width);  
8639                 }
8640                 renderer.renderEditor();
8641                 if(newRowsRenderedTable[0]==undefined)
8642                     newRowsRenderedTable[0] = new Array();
8643                 newRowsRenderedTable[0][cellIndex] = {"renderer":renderer, "column":column,"domCell":cell,"domRow":domRow,"validator":null,"rowIndex":0,"colIndex":cellIndex};
8644                 if(columns[cellIndex].visible){    
8645                     addRow.appendChild(cell);
8646                 }
8647             }                                                                                           
8648             table.appendChild(addRow); 
8649             table.appendChild(controlsRow);
8650         return [renderedTable, table, tableData, newRowsRenderedTable, columnClicksE];
8651         // Table of Cell Renderers, The Dom Table, the raw table data
8652     },function(value){
8653         return [value];
8654     }, sortedTableB);
8655     
8656     
8657     var renderedTableB = F.liftB(function(pageRendered){
8658         return pageRendered[0];
8659     }, pageRenderedB); 
8660     
8661     var domTableB = F.liftB(function(pageRendered){
8662         return pageRendered[1];
8663     }, pageRenderedB);
8664     
8665     var newRowsRenderedTableB = F.liftB(function(pageRendered){
8666         return pageRendered[3];
8667     }, pageRenderedB);  
8668     
8669     var columnClickedE = pageRenderedB.changes().mapE(function(pageRendered){
8670         return (pageRendered[4]);
8671     }).switchE();
8672     var columnClickedB = columnClickedE.startsWith(NOT_READY);
8673     
8674     
8675     
8676     
8677    /* var sortColumnB = F.liftB(function(columnClicked, data){
8678         if(!good()){
8679             return NOT_READY;
8680         }    
8681         var target = (columnClicked.target==undefined)?columnClicked.srcElement:columnClicked.target;
8682         var col = jQuery(target).parent().children().index(target);
8683         var columns = data["COLUMNS"];
8684         var count = 0;
8685         for(index in columns){
8686             if(count==col&&columns[index]['visible']){
8687                 log(columns[index]['reference']);
8688                 data['TABLEMETADATA']['sortColumn'] = columns[index]['reference'];
8689                 return data;
8690             }
8691             if(columns[index]['visible']){
8692                 count++;
8693             }               
8694         }
8695         return NOT_READY;
8696     }, columnClickedB, dataB);
8697 
8698     sortColumnB.changes().mapE(function(sortColumn){
8699         log("Sorting Column");
8700         dataB.sendEvent(sortColumn);
8701     });   */
8702     
8703     var filteredRowSelectionsB = F.liftB(function(rowSelections, renderedTable, newRowsRenderedTable){
8704             for(index in rowSelections){
8705                 var targetIndex = rowSelections[index];
8706                 if(targetIndex>renderedTable.length){
8707                     arrayCut(rowSelections, index);
8708                 }                                               
8709             }
8710         return rowSelections;
8711     }, rowSelectionsB, renderedTableB, newRowsRenderedTableB); 
8712    var rowSelectionsEmptyB = filteredRowSelectionsB.liftB(function(rowSelections){return rowSelections.length==0;});      
8713     
8714     
8715     var renderedRowSelectionsB = F.liftB(function(renderedTable, rowSelections){
8716         if(renderedTable==NOT_READY||rowSelections==NOT_READY){
8717             return NOT_READY; 
8718         }
8719         var c = document.createElement("div");
8720             for(index in renderedTable){   
8721                 var isSelected = arrayContains(rowSelections, parseInt(index)+1);
8722                 for(cellIndex in renderedTable[index]){
8723                     //log("Setting Selected");
8724                     renderedTable[index][cellIndex]["renderer"].setSelected(isSelected);
8725                 }
8726             }
8727     }, renderedTableB, rowSelectionsB);
8728     
8729     
8730        
8731     
8732     var tableAllowsAddB = dataB.liftB(function(tableData){
8733 	//log("tableAllowsAddB");
8734 	return (tableData["TABLEMETADATA"]!=undefined&&tableData["TABLEMETADATA"]['permissions']!=undefined&&tableData["TABLEMETADATA"]['permissions']['canAdd']!=undefined)?tableData["TABLEMETADATA"]['permissions']['canAdd']:true;
8735     });
8736     var tableAllowsDeleteB = dataB.liftB(function(tableData){
8737 	//log(tableAllowsDeleteB);
8738 	return (tableData["TABLEMETADATA"]!=undefined&&tableData["TABLEMETADATA"]['permissions']!=undefined&&tableData["TABLEMETADATA"]['permissions']['canDelete']!=undefined)?tableData["TABLEMETADATA"]['permissions']['canDelete']:true;
8739     });
8740     
8741     var tableDataChangedB = F.liftB(function(rendererTable, domTable){
8742         if(rendererTable==NOT_READY||rendererTable.length==0||domTable==NOT_READY)
8743             return F.receiverE().startsWith(NOT_READY);
8744 //	log("tableDataChangedB");
8745         var updateEvents = new Array();
8746         for(var rowIndex in rendererTable){
8747             for(var colIndex in rendererTable[rowIndex]){
8748                 
8749                 updateE = rendererTable[rowIndex][colIndex]["renderer"].getUpdateEvent();
8750                 updateEvents.push(updateE);
8751             }
8752         }                                                             
8753         //log("ZZZ");
8754         return F.mergeE.apply(this, updateEvents).startsWith(false);   
8755     },
8756     renderedTableB, domTableB).switchB();
8757     
8758    var userDataChangeB = F.orB(tableDataChangedB.changes().snapshotE(pageRenderedB).mapE(function(renderedData){
8759         // Table of Cell Renderers, The Dom Table, the raw table data
8760        // log("Checking Change");
8761         var rendererTable = renderedData[0];
8762         
8763         var domTable = renderedData[1];
8764         var columns = renderedData[2]["COLUMNS"];
8765         var dataTable = renderedData[2]["DATA"];
8766         /*var newRenderTable = renderedData[3]; */       
8767         for(var rowIndex in rendererTable){
8768             for(var colIndex in rendererTable[rowIndex]){
8769                 var renderCell = rendererTable[rowIndex][colIndex];
8770                 var dataCell = dataTable[rowIndex][colIndex];
8771                 //log("Getting Renderer Value");
8772                 
8773                 if(columns[colIndex].visible&&(renderCell["renderer"]).getValue()!=dataCell){
8774                     
8775    /*                log("DIFF");
8776                     log(renderCell["renderer"].getValue()+" != "+dataCell);
8777                 log(renderCell["renderer"]);
8778                 log(typeof(rowIndex)+" "+typeof(colIndex));
8779                 log(rowIndex+" "+colIndex);
8780                 log(renderCell);
8781                 log(dataCell);
8782                 log(dataTable);
8783                 log("/DIFF"); */
8784                     return true; 
8785                 
8786                 }
8787             } 
8788         }
8789         return false;
8790     }).startsWith(false), showAddRowsB); 
8791     
8792     F.liftB(function(userDataChange, confirmChanges){
8793         //log(userDataChange+" "+confirmChanges);
8794         if(userDataChange==NOT_READY||confirmChanges==NOT_READY){
8795             return NOT_READY;
8796         }
8797         
8798         if(userDataChange&&(!confirmChanges)){
8799             //log("Sending Update");
8800             triggerSaveE.sendEvent("ChangeEvent");
8801         }
8802     }, userDataChangeB, confirmChangesB);
8803     
8804     
8805     
8806     /*
8807     Gui Updates                     
8808     */
8809     F.insertValueB(F.ifB(F.andB(userDataChangeB, confirmChangesB), 'inline', 'none'),saveButton, 'style', 'display');
8810     F.insertValueB(F.ifB(F.andB(userDataChangeB, confirmChangesB), 'inline', 'none'),cancelButton, 'style', 'display');
8811     
8812     F.insertValueB(F.ifB(showAddRowsB, 'table-row', 'none'),addRow, 'style', 'display');
8813   
8814     F.insertValueB(F.ifB(F.andB(F.notB(showAddRowsB), tableAllowsAddB), 'inline', 'none'),addRowButton, 'style', 'display');
8815     F.insertValueB(F.ifB(rowSelectionsEmptyB, 'auto', 'pointer'),deleteRowButton, 'style', 'cursor');
8816     F.insertValueB(F.ifB(tableAllowsDeleteB, 'inline', 'none'),deleteRowButton, 'style', 'display');
8817     F.insertValueB(F.ifB(F.notB(rowSelectionsEmptyB), window['SETTINGS']['theme'].path+'delete.png', window['SETTINGS']['theme'].path+'delete_disabled.png'),deleteRowButton, 'src'); 
8818 
8819     /*
8820     Save Rows
8821     */
8822     cancelButtonPressedE.snapshotE(dataB).mapE(function(data){
8823         showAddRowsResetE.sendEvent(NOT_READY);
8824         dataB.sendEvent(data); 
8825     });
8826     saveButtonPressedE.snapshotE(F.liftB(function(pageRendered, showAddRows){return [pageRendered, showAddRows]}, pageRenderedB,showAddRowsB)).mapE(function(data){
8827 //log("saveButtonPressedE");    
8828     //log("save pressed");    
8829 	var renderedTable = data[0][0];
8830         var dataTable = data[0][2]["DATA"];
8831         var columns = data[0][2]["COLUMNS"];
8832         var newRenderedTable = data[0][3];  
8833         var renderRowIndex = renderedTable.length-1;
8834         var showAddRows = data[1];
8835         //log(data[2][0]);
8836         //log("ABOVE:"+data[2][0].length);                               
8837         if(renderedTable.length>dataTable.length){
8838         var dataRowIndex = dataTable.length;
8839         dataTable[dataRowIndex] = Array();
8840             for(c=0;c<renderedTable[renderRowIndex].length;c++){
8841                 var cell = renderedTable[renderRowIndex][c];
8842                //log("Save Button Get Renderer ");
8843                 var value = cell["renderer"].getValue();
8844                 dataTable[dataRowIndex][c] = value;
8845             }
8846         }
8847         else{
8848             r=0;
8849                 for(r=0;r<renderedTable.length;r++){
8850               //  log("Row "+r);
8851                     for(c=0;c<renderedTable[r].length;c++){
8852                         //log();
8853                         var cell = renderedTable[r][c];
8854                         //log("Save Button Get Renderer "); 
8855                         var value = cell["renderer"].getValue();
8856                         dataTable[r][c] = value;
8857                     }
8858                 }
8859                 if(showAddRows){
8860                 for(rowIndex=0;rowIndex<newRenderedTable.length;rowIndex++){
8861                     for(c=0;c<newRenderedTable[rowIndex].length;c++){
8862                         var cell = newRenderedTable[rowIndex][c];
8863                         //log("Save Button Get Renderer "); 
8864                         var value = cell["renderer"].getValue();
8865                         if(dataTable[rowIndex+r]==undefined)
8866                             dataTable[rowIndex+r] = new Array();
8867                         dataTable[rowIndex+r][c] = value;
8868                     }
8869                 }
8870             }    
8871         }
8872         pageRenderedB.sendEvent(data[0][2]);  
8873         showAddRowsResetE.sendEvent(NOT_READY);    
8874     });      
8875     
8876     
8877     /*
8878     Delete Rows
8879     */
8880     var pageDataAndRowSelectionsB = F.liftB(function(renderedData, rowSelections){
8881     if(renderedData==NOT_READY||rowSelections==NOT_READY){
8882         return NOT_READY;                         
8883     }
8884           //  log("Page and row selections");
8885         return {renderedData: renderedData, rowSelections: rowSelections};
8886     }, pageRenderedB, rowSelectionsB);
8887     var deleteTableRowsB = deleteButtonPressedE.snapshotE(pageDataAndRowSelectionsB).startsWith(NOT_READY);
8888     
8889     deleteTableRowsB.liftB(function(data){
8890         if(data==NOT_READY || data.rowSelections.length==0){
8891             return;
8892         }
8893         var rowSelections = data.rowSelections.reverse(); 
8894         var renderedTable = data.renderedData[0];
8895         var dataTable = data.renderedData[2]["DATA"];
8896         var columns = data.renderedData[2]["COLUMNS"];
8897         for(index=0;index<rowSelections.length;index++){
8898             arrayCut(data.renderedData[2]["DATA"], (rowSelections[index]-1));
8899         }      
8900         UI.confirm("Delete Rows", "Are you sure you wish to delete these "+rowSelections.length+" row(s)", "Yes", function(val){
8901             rowSelectionResetE.sendEvent(true);
8902             pageRenderedB.sendEvent(data.renderedData[2]);
8903         }, "No",
8904         function(val){
8905             rowSelectionResetE.sendEvent(true);
8906         }); 
8907     });
8908     
8909     domTableB.delayB(1000).liftB(function(domTable){
8910         /*jQuery(domTable).colResizable({
8911             liveDrag:true, 
8912             gripInnerHtml:"<div class='grip'></div>", 
8913             draggingClass:"dragging", 
8914             onResize:function(resize){
8915                 log(resize);
8916             }}); */
8917     });
8918     return domTableB
8919 }
8920 function getTableRowId(table, rowIndex){
8921     if(table.TABLEMETADATA!=undefined&&table.TABLEMETADATA['idColumn']!=undefined){
8922         var idColumnStr = table.TABLEMETADATA['idColumn'];
8923         var colIndex = getColumnIndex(table, idColumnStr);
8924         if(colIndex==null)
8925             return null;
8926         return table["DATA"][rowIndex][colIndex];
8927     }
8928     else
8929         log("Error, no id column specified in table meta data");
8930 }
8931 function getTableValue(table, rowIndex, columnName){
8932 	var colIndex = getColumnIndex(table, columnName);
8933     if(colIndex==null)
8934         return null;
8935     return table["DATA"][rowIndex][colIndex];
8936 }
8937 function getColumnIndex(table, columnName){
8938     for(colIndex in table["COLUMNS"]){
8939         if(table["COLUMNS"][colIndex]["reference"]==columnName){
8940             return colIndex;
8941         }
8942     }
8943     return null;
8944 }
8945 function JoinTableB(table1B, table2B, columnId){
8946     return F.liftBI(function(table1, table2){
8947         if(table1==NOT_READY||table2==NOT_READY){
8948             return NOT_READY;
8949         }
8950         var searchColIndex1 = columnId;
8951         for(colIndex in table1["COLUMNS"]){
8952             if(columnId==table1["COLUMNS"]["reference"]){
8953                 searchColIndex = colIndex;
8954                 break;
8955             }        
8956         }
8957         var searchColIndex2 = columnId;
8958         for(colIndex in table2["COLUMNS"]){
8959             if(columnId==table2["COLUMNS"]["reference"]){
8960                 searchColIndex = colIndex;
8961                 break;
8962             }        
8963         }
8964         
8965         /*for(property in table1){
8966             log(property);
8967             log(table1[property]);
8968         }*/  
8969         
8970         table1["COLUMNS"] = table1["COLUMNS"].concat(table2["COLUMNS"]);
8971         //table1["COLUMNMETADATA"] = table1["COLUMNMETADATA"].concat(table2["COLUMNMETADATA"]);
8972         for(rowIndex in table1["DATA"]){
8973             var searchCell1 = table1["DATA"][rowIndex][searchColIndex1];
8974             for(rowIndex2 in table2["DATA"]){
8975                 var searchCell2 = table2["DATA"][rowIndex2][searchColIndex2];
8976                 if(searchCell1==searchCell2){
8977                     for(colIndex2 in table2["DATA"][rowIndex2]){
8978                         table1["DATA"][rowIndex][table1["COLUMNS"].length+colIndex2] = table2["DATA"][rowIndex2][colIndex2];
8979                     }
8980                 }    
8981             }
8982         }
8983         return table1;
8984     }, function(mergeTable){
8985     
8986         return [table1, table2];
8987     }, table1B, table2B);
8988 }
8989 function FileUploaderDragDropWidget(instanceId,data){
8990     var UPLOAD = new AuroraUploadManager(); 
8991     var parent = this;
8992     var multiFile = (data.multiFile==undefined)?false:data.multiFile;
8993     var acceptedTypes = (data.acceptedTypes==undefined)?[]:data.acceptedTypes;                      
8994     var textStatus = DOM.createDiv(instanceId+"_status", "Drop Files Here");
8995     textStatus.className = "auroraUpload_dropZoneProgress";
8996     
8997     
8998     var dropHoverHtml = data.dropHoverHtml;
8999     
9000     
9001     var dropZone = DOM.createDiv(instanceId+"_dropZone"); 
9002     if(data.dropHtml!=undefined){
9003     	dropZone.innerHTML = data.dropHtml;
9004     }
9005     else{
9006     	dropZone.appendChild(textStatus);
9007     	dropZone.className = 'UploadDropZone';
9008     }
9009     
9010     //dropZone.style.display = 'inline-block';
9011     var width = data.placeholder.getAttribute('width');
9012     if(width==undefined){
9013     	width = data.placeholder.style.width.replace('px', '');
9014     }
9015     var height = data.placeholder.getAttribute('height');
9016     if(height==undefined){
9017     	height = data.placeholder.style.height.replace('px', '');
9018     }
9019     
9020     dropZone.style.width = width+'px';
9021     dropZone.style.height = height+'px';
9022     this.getDropZone = function(){return dropZone;};
9023     this.getPanel = function(){return textStatus;};
9024     this.loader=function(){     
9025         var dr = DOM.get((data.targetId!=undefined)?data.targetId:dropZone.id);
9026         //dr.style.backgroundColor = "#FF0000";
9027         var dropE = F.extractEventE(dr, 'drop').mapE(function(event){
9028             DOM.stopEvent(event); 
9029             //log(event);
9030             if(DOM.get(dropZone.id)){
9031                     DOM.get(dropZone.id).className = "UploadDropZone";
9032             }
9033             return event;    
9034         }); 
9035         this.dropE = dropE;
9036         var dragOverE = F.extractEventE(dr, 'dragover').mapE(function(event){
9037             DOM.stopEvent(event); 
9038             
9039             event.dataTransfer.dropEffect = 'move';
9040             
9041             if(data.dropHoverHtml!=undefined){
9042             	DOM.get(dropZone.id).innerHTML = data.dropHoverHtml;
9043             }
9044             else if(DOM.get(dropZone.id)){
9045                 DOM.get(dropZone.id).className = "UploadDropZoneHover";
9046             }
9047             return event;
9048         });
9049         
9050         var dragEnterE = F.extractEventE(dr, 'dragenter').mapE(function(event){
9051             DOM.stopEvent(event); 
9052             
9053             if(data.dropHoverHtml!=undefined){
9054             	DOM.get(dropZone.id).innerHTML = data.dropHoverHtml;
9055             }
9056             else if(DOM.get(dropZone.id)){
9057                 DOM.get(dropZone.id).className = "UploadDropZoneEnter";
9058             }
9059             return event;
9060         });
9061         
9062         var dragExitE = F.extractEventE(dr, 'dragleave').mapE(function(event){
9063             DOM.stopEvent(event); 
9064             if(data.dropHtml!=undefined){
9065             	DOM.get(dropZone.id).innerHTML = data.dropHtml;
9066             }
9067             else if(DOM.get(dropZone.id)){
9068                     DOM.get(dropZone.id).className = "UploadDropZone";
9069             }
9070             return event;
9071         });               
9072     
9073         var filesDropE = dropE.mapE(function(event){ 
9074             var files = event.target.files || event.dataTransfer.files;  
9075             var totalBytes = 0;
9076             var fileArray = [];
9077             for(fileIndex in files){
9078                 if(files[fileIndex].size!=undefined){
9079                
9080                     if(files[fileIndex].type!=""){
9081                         totalBytes+=files[fileIndex].size;
9082                         UPLOAD.add(files[fileIndex]);
9083                     }
9084                     else{
9085                         log("Unable to upload directories skipping "+files[fileIndex].type);
9086                     }
9087                 }
9088             }
9089             return {size: totalBytes, files:files};
9090         });
9091         this.filesDropE = filesDropE;
9092         this.uploadCompleteE = UPLOAD.uploadCompleteE;
9093         this.allUploadsCompleteE = UPLOAD.allUploadsCompleteE;
9094         //UPLOAD.allUploadsCompleteE;  
9095     
9096         var sendLoadStartE = UPLOAD.getUploader().sendLoadStartE.mapE(function(data){
9097             DOM.get(textStatus.id).innerHTML = "Uploading..."; 
9098         });
9099               
9100         var sendProgressE = UPLOAD.progressUpdateB.changes().filterE(function(val){return val!=NOT_READY;}).mapE(function(progress){
9101             // {total:totalSize, loaded:totalTransfered, currentTotal:progressUpdate.total, currentLoaded:progressUpdate.loaded};  
9102                var total = progress.currentTotal;
9103                var loaded = progress.currentLoaded;
9104                var currentPercentage = (loaded/total)*100;  
9105                
9106                var total = progress.total;
9107                var loaded = progress.loaded;
9108                var queuePercentage = (loaded/total)*100; 
9109                if(queuePercentage<0){
9110                 queuePercentage = 0;
9111                }    
9112                else if(queuePercentage>100){
9113                 queuePercentage = 100;
9114                }
9115                  
9116                /*if(DOM.get(textStatus.id)){
9117                 DOM.get(textStatus.id).innerHTML = percentage+"%";
9118                }    */
9119              return {filePercentageComplete:currentPercentage, queuePercentageComplete:queuePercentage,currentFile:progress.currentFile, rate:progress.rate, queue:progress.queue, formattedTotal:progress.formattedTotal}; 
9120         });      
9121 
9122         this.sendProgressE = sendProgressE;
9123         // totalProgressB               filePercentageComplete  queuePercentageComplete currentFile
9124         this.totalProgressB = F.liftB(function(progress){
9125             if(!good()){
9126                 return NOT_READY;
9127             }
9128             return progress;
9129         }, sendProgressE.startsWith(NOT_READY));
9130         
9131     }
9132     this.build=function(){
9133         if(!data.targetId){ 
9134             return dropZone.outerHTML;
9135         }
9136         //textStatus.innerHTML = "";
9137         return textStatus.outerHTML;
9138     }
9139     this.destroy=function(){
9140         /*log('Destroying FileUploader');
9141         document.getElementById(id).removeEventListener('drop', this.dragDrop);
9142         document.getElementById(id).removeEventListener('dragover', this.dragOver);
9143         */
9144     }
9145 }
9146   
9147      
9148 function FirstFileE(fileE){
9149     return fileE.mapE(function(event){ 
9150         var files = event.target.files || event.dataTransfer.files;    
9151         return files[0];
9152     });
9153 }
9154 function AuroraBlankFileUpload(fileE, url){
9155         this.sendLoadStartE = F.zeroE();     
9156         this.sendProgressE = F.zeroE();     
9157         this.uploadCompleteE = F.zeroE();                       
9158 }  
9159 function AuroraFileUpload(fileE, url){
9160     var uploadRequestE = fileE.mapE(function(fileData){
9161     	var file = fileData.file;
9162     	var path = fileData.path;
9163         var xhrObj = new XMLHttpRequest();  
9164         var upload = (xhrObj.upload!=undefined)?xhrObj.upload:xhrObj;
9165         var sendLoadStartE = F.extractEventE(upload, 'loadstart');     
9166         var sendProgressE = F.extractEventE(upload, 'progress');     
9167         var uploadCompleteE = F.receiverE();
9168             
9169         var parent = this;
9170         xhrObj.onreadystatechange = function(){
9171                     if (xhrObj.readyState == 4) {
9172                         if (xhrObj.status == 200) {                                                                                   
9173                             uploadCompleteE.sendEvent(jQuery.parseJSON(xhrObj.responseText));
9174                         }
9175                     }
9176         };
9177             if(file==NOT_READY){
9178                 return;
9179             }
9180             if(file.currentFile!=undefined){
9181                 file = file.currentFile;
9182             } 
9183         
9184             
9185         if(path!=undefined && path!=""){
9186         	path = "?path="+path;
9187         }
9188         else{
9189         	path = "";
9190         }
9191         
9192         xhrObj.open("POST", url+path, true);  
9193         xhrObj.setRequestHeader("Content-type", file.type);  
9194         xhrObj.setRequestHeader("X_FILE_NAME", file.name);  
9195         xhrObj.send(file);                 
9196         return {sendLoadStartE: sendLoadStartE, sendProgressE: sendProgressE, uploadCompleteE: uploadCompleteE};     
9197     });
9198         //Not happy about this recreate xmlhttpreq and then switch, but i had problems with reusing one xmlhttprequest object
9199     this.uploadCompleteE = uploadRequestE.mapE(function(uploadRequest){return uploadRequest.uploadCompleteE}).switchE();
9200     this.sendLoadStartE = uploadRequestE.mapE(function(uploadRequest){return uploadRequest.sendLoadStartE}).switchE();
9201     this.sendProgressE = uploadRequestE.mapE(function(uploadRequest){return uploadRequest.sendProgressE}).switchE();
9202 }  
9203 WIDGETS.register("FileUploaderDragDropWidget", FileUploaderDragDropWidget);
9204 
9205 function AuroraFileBrowserWidget(instanceId,data){
9206     data.targetId = instanceId+"_dropZone";
9207     var uploadWidget = new FileUploaderDragDropWidget(instanceId+"_dnd",data); 
9208     this.loader=function(){ 
9209           uploadWidget.loader();
9210          var directoryR = DATA.getRemote("aurora_directory", "resources/upload/"+window['SETTINGS']['user']['id']+"/", NOT_READY, POLL_RATES.SLOW);  //, NOT_READY, POLL_RATES.SLOW 
9211          var directoryB = directoryR.behaviour;
9212          
9213          var tableResetE = F.receiverE();
9214          
9215          uploadTotalProgressB = F.mergeE(uploadWidget.totalProgressB.changes().blindE(500), tableResetE).startsWith(NOT_READY);
9216          
9217          var filesTableB = F.liftBI(function(table, progress){
9218             if(table==NOT_READY){
9219                 return NOT_READY;
9220             }     
9221             var currentMatch = false;
9222             if(progress!=NOT_READY&&progress!=undefined){ 
9223                 var queue = progress.queue;
9224                 var currentFile = progress.currentFile;  
9225                 var progressIndex = getColumnIndex(table, "uploadprogress"); 
9226                 var newTable = table["DATA"];
9227                 if(queue.length>0){
9228                     currentMatch = false;
9229                     for(var queueIndex in queue){
9230                         var queueItem = queue[queueIndex]; 
9231                         var match = false;
9232                         for(var tableIndex in newTable){
9233                             var tableRow = newTable[tableIndex];
9234                             var filename = tableRow[getColumnIndex(table, "filename")];
9235                             var currentProgress = tableRow[progressIndex];
9236                             if(filename==queueItem.name && (currentProgress!=""&& currentProgress!=undefined)){
9237                                 match = true;
9238                             }       
9239                             
9240                             //TODO: sometimes FF will crash with lots of files
9241                             if(currentProgress!=""&&currentProgress!=undefined){
9242                             
9243                                 if(currentFile.name==filename){
9244                                     newTable[tableIndex] = [currentFile.type, currentFile.name, currentFile.name, "", currentFile.size, currentFile.type, Math.ceil(progress.filePercentageComplete)];
9245                                     currentMatch = true;
9246                                     
9247                                 }
9248                                 else if(!isNaN(table["DATA"][tableIndex][progressIndex])){
9249                                     table["DATA"][tableIndex][progressIndex] = 100;    
9250                                 }
9251                             }                                                   
9252                         }
9253                         if(!match){
9254                             newTable.push([queueItem.type, queueItem.name, queueItem.name, "", queueItem.size, queueItem.type, (queueItem.name==currentFile.name)?Math.ceil(progress.filePercentageComplete):"Waiting..."]);
9255                         }
9256                     }
9257                     if(!currentMatch){
9258                         newTable.push([currentFile.type, currentFile.name, currentFile.name, "", currentFile.size, currentFile.type, Math.ceil(progress.filePercentageComplete)]);
9259                     }              
9260                     
9261                     
9262                 }
9263                 else{
9264                     var match = false;
9265                     for(var tableIndex in newTable){
9266                         var tableRow = newTable[tableIndex];
9267                         var filename = tableRow[getColumnIndex(table, "filename")];
9268                         var currentProgress = tableRow[progressIndex];
9269                         if(currentProgress!=""&& currentProgress!=undefined){
9270                             if(filename==currentFile.name){
9271                                 newTable[tableIndex] = [currentFile.type, currentFile.name, currentFile.name, "", currentFile.size, currentFile.type, Math.ceil(progress.filePercentageComplete)];
9272                                 match = true;
9273                             }      
9274                             else if(!isNaN(table["DATA"][tableIndex][progressIndex])){
9275                                     table["DATA"][tableIndex][progressIndex] = 100;    
9276                             }
9277                         }
9278                     }
9279                     if(!match){
9280                         newTable.push([currentFile.type, currentFile.name, currentFile.name, "", currentFile.size, currentFile.type, Math.ceil(progress.filePercentageComplete)]); 
9281                     }
9282                     
9283                 }   
9284                 //Remove old uploads
9285                 for(var tableIndex in newTable){
9286                     var tableRow = newTable[tableIndex];
9287                     var currentProgress = tableRow[getColumnIndex(newTable, "uploadprogress")]; 
9288                     if(currentProgress!="" && currentProgress!=undefined){
9289                         var match = false; 
9290                         for(var queueIndex in queue){
9291                             var queueItem = queue[queueIndex];
9292                             if(filename==queueItem.name){
9293                                 match = true;
9294                                 break;
9295                             }
9296                         }
9297                         if(!match || Math.ceil(currentProgress)==100){
9298                             tableRow = tableRow.splice(tableIndex, 1);         
9299                         }
9300                     }
9301                 } 
9302             } 
9303             else{
9304                 for(var rowIndex in table["DATA"]){   
9305                     table["DATA"][rowIndex][progressIndex] = "";
9306                 } 
9307             }  
9308               
9309             var filenameIndex = getColumnIndex(table, "filename");
9310             var typeIndex = getColumnIndex(table, "type");
9311             var filesizeIndex = getColumnIndex(table, "filesize");
9312             var uploadProgressIndex = progressIndex;
9313             
9314             
9315             
9316             var filenameSorter = function(row1, row2){
9317                 if((row1[typeIndex]=="directory"||row2[typeIndex]=="directory") && (row1[typeIndex]!=row2[typeIndex])){   //XOR
9318                     return (row1[typeIndex]=="directory")?-1:1;
9319                 }
9320                 return row1[filenameIndex].localeCompare(row2[filenameIndex]);
9321             };
9322             table.TABLEMETADATA['sortColumn'] = filenameIndex;
9323             table.TABLEMETADATA['sortOrder'] = "DESC";
9324             if(table.COLUMNMETADATA[filenameIndex]==undefined){
9325                 table.COLUMNMETADATA[filenameIndex] = {"sorter":filenameSorter};
9326             }
9327             else{
9328                 table.COLUMNMETADATA[filenameIndex]["sorter"] = filenameSorter;   
9329             }
9330             if(table.COLUMNMETADATA[filesizeIndex]==undefined){
9331                 table.COLUMNMETADATA[filesizeIndex] = {"renderer":new FileSizeRendererColumn()};
9332             }
9333             else{  
9334                 table.COLUMNMETADATA[filesizeIndex]["renderer"] = new FileSizeRendererColumn();
9335             }
9336             if(table.COLUMNMETADATA[typeIndex]==undefined){
9337                 table.COLUMNMETADATA[typeIndex] = {"renderer":new FileTypeRendererColumn()};
9338             }
9339             else{ 
9340                 table.COLUMNMETADATA[typeIndex]["renderer"] = new FileTypeRendererColumn();
9341             }
9342             
9343             if(table.COLUMNMETADATA[uploadProgressIndex]==undefined){
9344                 table.COLUMNMETADATA[uploadProgressIndex] = {"renderer":new UploadProgressColumnRenderer()};
9345             }
9346             else{ 
9347                 table.COLUMNMETADATA[uploadProgressIndex]["renderer"] = new UploadProgressColumnRenderer();
9348             }
9349             return table;   
9350          },
9351          function(table){
9352             return [table, NOT_READY];
9353          }, directoryB, uploadTotalProgressB);         
9354          tableBI = TableWidgetB(instanceId+"_table", data, filesTableB);      
9355          F.insertDomB(tableBI, instanceId+"_container");  
9356         
9357          tableBI.liftB(function(table){
9358             if(!good()){
9359                 return NOT_READY;
9360             }
9361             var width = table.scrollWidth;
9362             DOM.get(instanceId+"_downloadQueue").style.width=width+"px";
9363          }); 
9364          
9365          uploadWidget.totalProgressB.liftB(function(uploadProgress){
9366             if(!good()){
9367                 return NOT_READY;
9368             }                                              
9369             var updateCallback = function(){
9370                 jQuery("#"+instanceId+"_totalProgress").progressbar("value", uploadProgress.queuePercentageComplete).children('.ui-progressbar-value').html("("+uploadProgress.queuePercentageComplete.toPrecision(3)+"%)").css("display", "block"); 
9371                 
9372             };
9373 
9374             if(DOM.get(instanceId+"_downloadQueue").style.display=="none"){
9375                 jQuery("#"+instanceId+"_totalProgress").progressbar({value:0});
9376                 jQuery("#"+instanceId+"_downloadQueue").slideDown(300, updateCallback);
9377             }
9378             else{
9379                 updateCallback();
9380             }
9381          });  
9382          
9383          uploadWidget.totalProgressB.blindB(1000).liftB(function(uploadProgress){
9384             if(!good()){
9385                 return NOT_READY;
9386             }   
9387             DOM.get(instanceId+"_currentFile").innerHTML = "";                                            
9388             if(uploadProgress.rate!="0"){
9389                 
9390             DOM.get(instanceId+"_rate").innerHTML = "Transferring "+uploadProgress.formattedTotal+" at "+uploadProgress.rate;
9391             }
9392          });
9393          uploadWidget.allUploadsCompleteE.mapE(function(uploadComplete){
9394             jQuery("#"+instanceId+"_totalProgress").progressbar("value", 100);   
9395             DOM.get(instanceId+"_currentFile").innerHTML = "Upload Complete";
9396             tableResetE.sendEvent(NOT_READY);
9397          }).delayE(3000).mapE(function(){jQuery("#"+instanceId+"_downloadQueue").slideUp(1000);});
9398          
9399          
9400          uploadWidget.dropE.mapE(function(drop){   
9401 
9402          }); 
9403          
9404           
9405     }
9406     this.build=function(){
9407         
9408         return "<div id=\"logger\"></div><span id=\""+instanceId+"_dropZone\" style=\"background-color: #FF0000;\"><span id=\""+instanceId+"_container\"> </span><div id=\""+instanceId+"_downloadQueue\" style=\"display:none\"><div id=\""+instanceId+"_innerDownloadQueue\" class=\"auroraUploadQueue\"><div id=\""+instanceId+"_currentFile\"></div><div id=\""+instanceId+"_rate\"></div><div id=\""+instanceId+"_fileProgress\"></div><div id=\""+instanceId+"_totalProgress\"></div></div><span style=\"clear: both;\"></span></div></span>";  
9409     }
9410     this.destroy=function(){
9411         uploadWidget.destroy(); 
9412     }
9413 }
9414 WIDGETS.register("AuroraFileBrowserWidget", AuroraFileBrowserWidget);
9415 
9416 function AuroraUploadManager(args){
9417    
9418     // sendLoadStartE sendProgressE  uploadCompleteE
9419     var queue = new AuroraTaskQueue();
9420     var uploader = new AuroraFileUpload(queue.dequeueEventE, window['SETTINGS']['scriptPath']+"request/aurora.uploader");     
9421     this.getUploader = function(){
9422         return uploader;
9423     };
9424     this.add = function(upload, path){
9425     	if(path==undefined&&args!=undefined&&args.path!=undefined){
9426     		path = args.path;
9427     	}
9428         queue.enqueue({file: upload, path: path});
9429     };
9430     this.progressUpdateE = uploader.sendProgressE.mapE(function(progress){
9431         return progress;
9432     });
9433     this.uploadCompleteE = uploader.uploadCompleteE.mapE(function(upload){
9434         queue.next();
9435         return upload;
9436     });
9437     this.allUploadsCompleteE = queue.finishedE.mapE(function(complete){
9438         return complete;
9439     });
9440     
9441     
9442     this.uploadStartedE = queue.kickstartE;   
9443     
9444     this.dequeueEventE = queue.dequeueEventE;    
9445     var lastStamp = undefined;
9446     var lastBytes = undefined;  
9447     this.progressUpdateB = F.liftB(function(allQueue, queue, progressUpdate, currentItem){
9448         if(!good()){
9449             return NOT_READY;                             
9450         }   
9451         var currentFile = currentItem.file;
9452         var path = currentFile.path;
9453         log(currentItem);
9454         var totalSize = 0;
9455         var totalTransfered = progressUpdate.loaded;
9456         for(index in allQueue){    
9457             var file = allQueue[index].file;  
9458             var name = file.name;
9459             var size = file.size;
9460             totalSize+=size;
9461             if(name==currentFile.name){
9462                 continue;
9463             } 
9464             var match = false;
9465             for(index in queue){
9466                 if(queue[index].file.name == name){
9467                     match=true;
9468                     break;
9469                 }
9470             }
9471             if(!match){
9472                 totalTransfered+=size;    
9473             }
9474         }
9475     stamp = new Date().getTime();
9476     var rate = 0;
9477     
9478     
9479     if(lastStamp!=undefined){
9480         var timeDiff = (stamp-lastStamp)/1000;
9481         var bytesDiff = (totalTransfered-lastBytes);
9482         if(bytesDiff>0){
9483             rate = (bytesDiff*8)/timeDiff;
9484             
9485             if(rate>1000000000000){
9486                 rate = (rate/1000000000000).toFixed(2)+" Tbps";    
9487             }
9488             else if(rate>1000000000){
9489                 rate = (rate/1000000000).toFixed(2)+" Gbps";    
9490             }
9491             else if(rate>1000000){
9492                 rate = (rate/1000000).toFixed(2)+" Mbps";    
9493             }
9494             else if(rate>1000){
9495                 rate = (rate/1000).toFixed(2)+" Kbps";    
9496             }
9497             else rare = rate+" Bps"
9498         }
9499     }    
9500     var formattedTotal = totalSize;
9501             if(totalSize>1000000000000){
9502                 formattedTotal = (totalSize/1000000000000).toFixed(2)+" TB";    
9503             }
9504             else if(totalSize>1000000000){
9505                 formattedTotal = (totalSize/1000000000).toFixed(2)+" GB";    
9506             }
9507             else if(totalSize>1000000){
9508                 formattedTotal = (totalSize/1000000).toFixed(2)+" MB";    
9509             }
9510             else if(totalSize>1000){
9511                 formattedTotal = (totalSize/1000).toFixed(2)+" KB";    
9512             }
9513             else formattedTotal = totalSize+" Bps";
9514             
9515     lastBytes = totalTransfered;
9516     lastStamp = stamp;
9517     var ob = {total:totalSize, loaded:totalTransfered, currentTotal:progressUpdate.total, currentLoaded:progressUpdate.loaded, currentFile:currentFile, rate: rate, queue:queue, formattedTotal:formattedTotal};
9518     return ob;
9519     }, queue.jobQueueE.startsWith(NOT_READY), queue.queueB, this.progressUpdateE.startsWith(NOT_READY), this.dequeueEventE.startsWith(NOT_READY));
9520     
9521     
9522 }
9523 
9524 
9525 
9526 
9527 /**
9528  *  FileSizeRendererColumn
9529  * @constructor
9530  */
9531 function UploadProgressColumnRenderer(){
9532     this.getCellRenderer = function(value, cell, width){
9533         if(cell==undefined){
9534             return null;
9535         }       
9536         return new UploadProgressCellRenderer(value, cell, width);    
9537     }
9538 }
9539 /**
9540  *  UploadProgressCellRenderer
9541  * @constructor
9542  */
9543 function UploadProgressCellRenderer(value, cell, width){    
9544     var rValue = value; 
9545     var container = DOM.createDiv(undefined,undefined,"UploadProgressCellRenderer");
9546     cell.appendChild(container);
9547     
9548     this.render = function(){         
9549         if(rValue=="" || isNaN(rValue)){
9550             container.innerHTML = rValue;
9551         }
9552         else{
9553             jQuery(container).each(function() {
9554                 jQuery(this).progressbar({
9555                     value: rValue
9556                 }).children('.ui-progressbar-value').html("("+rValue.toPrecision(3)+"%)").css("display", "block");
9557 
9558             });
9559         }  
9560     }
9561     this.render();
9562     this.getValue = function(){
9563         return rValue;
9564     }
9565     this.renderEditor = function(){
9566          
9567     }
9568     this.setSelected = function(selected){ 
9569         if(selected){
9570             cell.className="TableWidgetCellSelected"; 
9571            // cell.style.backgroundColor=tableBackgroundColorSelected; 
9572         }                                  
9573         else{
9574             cell.className="TableWidgetCell"; 
9575             //cell.style.backgroundColor=tableBackgroundColor; 
9576         }
9577     }
9578     this.setValue = function(newValue){
9579         rValue = newValue;
9580         this.render();
9581     }
9582     this.getUpdateEvent = function(){
9583         return F.zeroE();
9584     }
9585      
9586 }
9587 function pushToValidationGroupBehaviour(key, validationGroupB, val){                    
9588     log(arguments);
9589 	if(val==NOT_READY)
9590         return;
9591     var validationGroup = validationGroupB.valueNow();
9592     validationGroup[key] = val;
9593     validationGroupB.sendEvent(validationGroup);
9594 }
9595 function PhoneNumbersWidget(instanceId, data){
9596     this.instanceId = instanceId;
9597     this.loader=function(){  
9598     	var valueName = (data.name==undefined)?"ContactNumbers":data.name;
9599     	var line = "<input type=\"text\" /><select><option>Mobile</option><option>Home</option><option>Work</option></select><span class=\"button\">Add Number</span>";
9600     	var columns = [{"reference": "behaviour", "display": "Number", "type": "string", "visible":true, "readOnly": false},
9601     	               {"reference": "behaviour", "display": "Type", "type": "string", "visible":true, "readOnly": false}];
9602     	var tableB = F.receiverE().startsWith({"DATA": [["",""]], "COLUMNS": columns, "TABLEMETADATA": {"permissions": {"canAdd": true, "canDelete": true, "canEdit": true}}, "ROWMETADATA": [], "CELLMETADATA": [[]], "COLUMNMETADATA": []});
9603     	var tableBI = F.liftBI(function(table){
9604              var renderer = new BasicSelectCellRendererContainer([{"display": "Mobile", value: "Mobile"}, {"display": "Home", "value": "Home"}, {"display": "Work", "value": "Work"}]);
9605              table.COLUMNMETADATA[1] = {"renderer": renderer};  
9606     		return table;
9607     	}, function(table){return [table];}, tableB);
9608     	F.insertDomB(TableWidgetB(instanceId+"_table", data, tableBI), instanceId+"_container");
9609     	
9610     	var formGroupB = DATA.get(data.formGroup, undefined, {});
9611         var widgetValueB = F.liftB(function(table){
9612             if(!good()){
9613             	return {value: table.DATA, valid: false, name: valueName};
9614             }
9615             return {value: table, valid: (table.DATA.length>0&&table.DATA[0].length>0&&table.DATA[0][0].length>0), name: valueName};
9616         },tableBI);
9617         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB); 
9618     }                    
9619     this.build=function(){
9620         return "<div id=\""+instanceId+"_container\"></div>";   //"+scriptPath+"themes/"+theme+"/loading_s.gif
9621     }
9622 } 
9623 function EmailConfirmer(instanceId, data){
9624     var id = "emailConfirmer_"+instanceId;     
9625     this.instanceId = instanceId;
9626     this.loader=function(){  
9627     	var manualSetB = DATA.getB(data.name+"_man");
9628     	var userDefault = (data.userDefault==undefined)?false:data.userDefault;
9629     	var valueName = (data.name==undefined)?"Email":data.name;
9630     	var allowBlank = (data.allowBlank==undefined)?false:data.allowBlank;
9631         
9632         if(userDefault){
9633         	var currentUserB = DATA.getRemote("aurora_current_user").behaviour; 
9634         	currentUserB.liftB(function(user){
9635 				if(!good()){
9636 					return NOT_READY;
9637 				}
9638 				DOM.get(data.target).value = user.email;
9639 				manualSetB.sendEvent({value: user.email, valid: true, name: valueName});
9640 			});
9641         	
9642         }
9643         
9644         var emailBlurE = F.extractEventE(data.target, 'blur');
9645         var emailValueB = F.extractValueB(data.target);
9646         var emailRequestB = emailBlurE.snapshotE(emailValueB).mapE(function(text){return {email: ""+text};}).startsWith(NOT_READY);
9647         var emailValidE = getAjaxRequestB(emailRequestB, SETTINGS['scriptPath']+"request/form_validator_check_email/").mapE(function(data){return data.valid;});
9648         var emailValidB = emailValidE.startsWith(NOT_READY);
9649         var formGroupB = DATA.get(data.formGroup, undefined, {});
9650         var widgetValueB = F.liftB(function(emailValid, emailValue, manualSet){
9651         	if((emailValue==NOT_READY&&manualSet!=NOT_READY)||(manualSetB.firedAfter(emailValueB))){
9652         		return manualSet;
9653             }
9654             if(allowBlank&&emailValue==''){
9655             	return {value: emailValue, valid: true, name: valueName};	
9656             }
9657         	if(emailValid==NOT_READY){
9658         		return NOT_READY;
9659         	}
9660             return {value: emailValue, valid: emailValid, name: valueName};
9661         },emailValidB, emailValueB, manualSetB);
9662         
9663         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB); 
9664         
9665         widgetValueB.liftB(function(widgetValueB){
9666         	if(widgetValueB==NOT_READY){
9667         		document.getElementById(data.target).className = 'form_validator_validInput';
9668                 
9669         	}
9670         	else {
9671         		document.getElementById(data.target).className = (widgetValueB.valid)?'form_validator_validInput':'form_validator_invalidInput';
9672         		document.getElementById(id).src = (widgetValueB.valid)?window['SETTINGS']['theme']['path']+'tick.png':window['SETTINGS']['theme']['path']+'cross.png';
9673         	}
9674             }); 
9675         emailBlurE.mapE(function(){document.getElementById(id).src=SETTINGS['themeDir']+'loading_s.gif';});                                                                           
9676     }                    
9677     this.build=function(){
9678         return "<img src=\"/resources/trans.png\" alt=\"\" class=\"loadingSpinner\" id=\""+id+"\" />";   //"+scriptPath+"themes/"+theme+"/loading_s.gif
9679     }
9680 }        
9681 function ValidatedSubmitButton(instanceId, data){
9682     this.elementId = instanceId+'_submit';  
9683     this.loader=function(){
9684         var formGroupB = DATA.get(data.formGroup, undefined, {});
9685         var groupValidB = formGroupB.liftB(function(validationMap){
9686             //seperate validation behaviour from value beahviour
9687             return F.liftB.apply(this,[function(){
9688             	var trueCount=0;
9689             	log("Submit Buton");
9690             	log(arguments);
9691                 for(index in arguments){
9692                 	if(!arguments[index].valid){
9693                         
9694                         return false;
9695                     }
9696                     else{
9697                         //log("TRUE");
9698                     }
9699                     trueCount++;
9700                 }
9701                 return true;
9702             }].concat(getObjectValues(validationMap)));
9703         }).switchB();
9704         //var groupValidB = F.receiverE().startsWith(NOT_READY);
9705         var elementId = this.elementId;
9706         jQuery("#"+elementId).button();
9707         groupValidB.liftB(function(valid){
9708         	jQuery("#"+elementId).button((valid)?'enable':'disable');
9709         });
9710     }
9711     this.build=function(){
9712         return "<input type=\"submit\" value=\"Submit\" id=\""+this.elementId+"\" />";       
9713     }    
9714 }
9715 function ValidatedTextBox(instanceId, data){;
9716     this.instanceId = instanceId;
9717     this.loader=function(){    
9718     	var manualSetB = DATA.getB(data.name+"_man");
9719     	var valueName = (data.name==undefined)?"Email":data.name; 
9720         var formGroupB = DATA.get(data.formGroup, undefined, {}); 
9721         var txtValueB = F.extractValueB(this.instanceId);
9722        
9723         var validB = txtValueB.liftB(function(text){
9724             if(data.minChars && text.length<data.minChars)
9725                 return false;
9726             if(data.maxChars && text.length>data.maxChars)
9727                 return false;
9728             return true;
9729         });
9730         var widgetResponseB = F.liftB(function(valid, text, manualSet){//
9731         	if((text==NOT_READY&&manualSet!=NOT_READY)||(manualSetB.firedAfter(txtValueB))){
9732         		return manualSet;
9733              }
9734         	if(valid==NOT_READY||text==NOT_READY||text==null){
9735             	return NOT_READY;
9736             }
9737             
9738             document.getElementById(instanceId).className = (text.length==0)?'':((valid)?'form_validator_validInput':'form_validator_invalidInput');
9739             return {value: text, valid: valid, name: valueName};
9740         }, validB, txtValueB, manualSetB);//  
9741         
9742         //pushToValidationGroupBehaviour(instanceId, validationGroupB, validB);
9743         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetResponseB);  
9744     }      
9745     this.build=function(){
9746         var size = (data.size==undefined)?"":" size=\""+data.size+"\"";
9747         return "<input type=\"text\" value=\"\" id=\""+this.instanceId+"\" "+size+" />";                   //disabled=\"disabled\"
9748     }
9749 }     
9750 
9751 function ValidatedSelectField(instanceId, data){;
9752     this.instanceId = instanceId;
9753     this.loader=function(){    
9754         var valueName = (data.name==undefined)?"SelectField":data.name; 
9755         var formGroupB = DATA.get(data.formGroup, undefined, {}); 
9756         var selectValueB = F.extractValueB(this.instanceId);
9757         var validB = selectValueB.liftB(function(text){
9758             return true;
9759         });
9760         var widgetResponseB = F.liftB(function(valid, text){
9761             if(!good()||text==null){
9762                 return NOT_READY;
9763             }
9764             document.getElementById(instanceId).className = (text.length==0)?'':((valid)?'form_validator_validInput':'form_validator_invalidInput');
9765             return {value: text, valid: valid, name: valueName};
9766         }, validB, selectValueB);  
9767         
9768         //pushToValidationGroupBehaviour(instanceId, validationGroupB, validB);
9769         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetResponseB);  
9770     }      
9771     this.build=function(){
9772         var select = DOM.create('select');
9773         select.id = this.instanceId;
9774         for(index in data.options){
9775             select.appendChild(DOM.createOption(this.instanceId+"_"+index, undefined, data.options[index]+"", index+""));
9776         }
9777         return select;         
9778     }
9779 } 
9780                                   
9781 function ValidatedTextArea(instanceId, data){
9782     this.instanceId = instanceId;
9783     this.loader=function(){      
9784     	//log("TEXTAREA");
9785     	var valueName = (data.name==undefined)?"TextArea":data.name;
9786     	//log(valueName);
9787         var formGroupB = DATA.get(data.formGroup, undefined, {}); 
9788         var txtValueB = F.extractValueB(this.instanceId);
9789         
9790         var manualSetB = DATA.getB(data.name+"_man");
9791         manualSetB.liftB(function(manualSet){
9792         	
9793         	//log("manualSetB CHANGE ");
9794         	//log(manualSet);
9795         });
9796         
9797         
9798         
9799         var validB = txtValueB.liftB(function(text){
9800             if(data.minChars && text.length<data.minChars)
9801                 return false;
9802             if(data.maxChars && text.length>data.maxChars)
9803                 return false;
9804             return true;
9805         });
9806         var widgetValueB = F.liftB(function(valid, text, manualSet){
9807         	if(manualSetB.firedAfter(txtValueB)){
9808         		return manualSet;
9809             }
9810         	if(text==NOT_READY||text==null||valid==NOT_READY){
9811                 return NOT_READY;
9812             }
9813             
9814             document.getElementById(instanceId).className = (text.length==0)?'':((valid)?'form_validator_validInput':'form_validator_invalidInput');
9815             return {valid: valid, value: text, name: valueName};
9816         }, validB,txtValueB,manualSetB);  
9817         
9818         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB);    
9819     }      
9820     this.build=function(){
9821         var cols = 10;
9822         if(data.cols)
9823             cols = data.cols;
9824         var rows = 5;
9825         if(data.rows)
9826             rows = data.rows;
9827         return "<textarea type=\"text\" id=\""+this.instanceId+"\" rows=\""+rows+"\" cols=\""+cols+"\"></textarea>";       
9828     }
9829 }                                              
9830 function ValidatedCheckBox(instanceId, data){   
9831     this.instanceId = instanceId;
9832     this.loader=function(){
9833         var valueName = (data.name==undefined)?"Checkbox":data.name;
9834         var formGroupB = DATA.get(data.formGroup, undefined, {}); 
9835         var validB = jQuery("#"+instanceId+"_checkbox").fj('jQueryBind', 'change').mapE(function(event){
9836             return DOM.get(instanceId+"_checkbox").checked;
9837         }).startsWith(false);
9838         var widgetValueB = F.liftB(function(valid){
9839             if(!good()){
9840                 return NOT_READY;
9841             }
9842             //DOM.get(instanceId).className = ((valid)?'form_validator_validInput':'form_validator_invalidInput');
9843             return {valid: valid, value: valid, name: valueName};
9844         },validB);  
9845         
9846         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB);   
9847     }      
9848     this.build=function(){
9849         return "<span id=\""+instanceId+"\"><input type=\"checkbox\" id=\""+this.instanceId+"_checkbox\" /></span>";       
9850     }
9851 }
9852 
9853 function ValidatedPasswordWidget(instanceId, data){
9854     this.instanceId = instanceId;
9855     this.loader=function(){       
9856         
9857     	var manualSetB = DATA.getB(data.name+"_man");
9858     	
9859     	var valueName = (data.name==undefined)?"Password":data.name;
9860         var formGroupB = DATA.get(data.formGroup, undefined, {}); 
9861         var txtValue1B = F.extractValueB(this.instanceId+"_pass1");
9862         var txtValue2B = F.extractValueB(this.instanceId+"_pass2");
9863         
9864         var validB = F.liftB(function(text1, text2){
9865             if(!good()||(text1.length==0||text2.length==0)){
9866                 return NOT_READY;
9867             }
9868             if(data.minChars && text1.length<data.minChars)
9869                 return false;
9870             if(data.maxChars && text1.length>data.maxChars)
9871                 return false;
9872             if(data.minChars && text2.length<data.minChars)
9873                 return false;
9874             if(data.maxChars && text2.length>data.maxChars)
9875                 return false;
9876             if(text1!=text2)
9877                 return false;
9878             return true;
9879         }, txtValue1B, txtValue2B);
9880         var widgetValueB = F.liftB(function(valid, text, manualSet){
9881         	if((txtValue1B==NOT_READY&&manualSet!=NOT_READY)||(manualSetB.firedAfter(txtValue1B))){
9882         		return manualSet;
9883              }
9884         	if(!good()||text==null){
9885                 return {valid: false, value: "", name: valueName};
9886             }
9887             document.getElementById(instanceId+"_pass1").className = (text.length==0)?'':((valid)?'form_validator_validInput':'form_validator_invalidInput');
9888             document.getElementById(instanceId+"_pass2").className = (text.length==0)?'':((valid)?'form_validator_validInput':'form_validator_invalidInput'); 
9889             document.getElementById(instanceId+"_tick").src = (valid)?window['SETTINGS']['theme']['path']+'tick.png':window['SETTINGS']['theme']['path']+'cross.png';
9890             //log({valid: valid, value: text, name: valueName});
9891             return {valid: valid, value: text, name: valueName};
9892         },validB,txtValue1B, manualSetB);  
9893         
9894         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB);    
9895     }             
9896     this.build=function(){
9897         return "<input type=\"password\" id=\""+this.instanceId+"_pass1\" /> <img src=\"/resources/trans.png\" alt=\"\" class=\"loadingSpinner\" id=\""+this.instanceId+"_tick\" /><br /><input type=\"password\" id=\""+this.instanceId+"_pass2\" />";       
9898     }
9899 }
9900 function ValidatedCalendar(instanceId, data){
9901     this.instanceId = instanceId;
9902     this.inputId = instanceId+"_input"   
9903     
9904     this.loader=function(){       
9905         var formGroupB = DATA.get(data.formGroup, undefined, {});  
9906         var valueName = (data.name==undefined)?"Email":data.name;
9907         var dateE = F.receiverE();
9908         var dateB = dateE.startsWith(null);
9909         var validB = dateB.liftB(function(val){return val!=null});
9910         jQuery("#"+instanceId).datepicker({changeYear: true,yearRange:"-110:+0", onSelect: function(dateText, inst) {dateE.sendEvent(dateText);}});    
9911         
9912         
9913         var widgetValueB = F.liftB(function(valid, text){
9914             if(!good()||text==null){
9915                 return NOT_READY;
9916             }
9917             
9918             document.getElementById(instanceId).className = (text.length==0)?'':((valid)?'form_validator_validInput':'form_validator_invalidInput');
9919             return {valid: valid, value: text, name: valueName};
9920         },validB,dateB);  
9921         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB);  
9922     }      
9923     this.build=function(){
9924         return "<span id=\""+instanceId+"\"></span>";//"<input id=\""+this.inputId+"\" type=\"text\">";         
9925     }
9926 }
9927 
9928         //.onSelect = function(x){alert(x);dateE.sendEvent(x);};
9929         //jQuery.datepicker._defaults.onSelect = function(text, inst){alert(text)};
9930        //jQuery("#"+instanceId).fj('jQueryBind', 'change').mapE(function(e){showObj(e);});
9931         //{onSelect: function(dateText, inst) {formGroup.push(data.name,dateText);}}
9932         //jQuery("#"+instanceId).fj('jQueryBind', 'onSelect').mapE(function(x){alert(x);});
9933         //jQuery("#"+instanceId).fj('jQueryBind', 'dateSelected').mapE(function(x){showObj(x);});
9934         //var calendarB = jQuery("#"+instanceId).fj('extEvtE', 'onSelect').mapE(function(x){alert(x);});
9935         //var calendarB = jQuery("#"+instanceId).fj('extValB').liftB(function(x){alert(x);});
9936 
9937 //widgetTypes['contactFormSubmitButton']=ContactFormSubmitButton;
9938                                   
9939 WIDGETS.register("ValidatedPasswordWidget", ValidatedPasswordWidget); 
9940 WIDGETS.register("ValidatedSubmitButton", ValidatedSubmitButton);
9941 WIDGETS.register("ValidatedCalendar", ValidatedCalendar);
9942 WIDGETS.register("ValidatedTextArea", ValidatedTextArea);
9943 WIDGETS.register("ValidatedTextBox", ValidatedTextBox);
9944 WIDGETS.register("EmailConfirmer", EmailConfirmer);
9945 WIDGETS.register("ValidatedSelectField", ValidatedSelectField);
9946 WIDGETS.register("ValidatedCheckBox", ValidatedCheckBox);  
9947 WIDGETS.register("PhoneNumbersWidget", PhoneNumbersWidget);  
9948 
9949 var minChars = 1;
9950 var maxChars = 30;
9951 function checkCharLength(text){
9952     if(text.length<1)
9953         return false;
9954     if(text.length>30)
9955         return false;
9956     return true;
9957 }     
9958 function ValidatedContactForm(instanceId, data){
9959     var widgetId = instanceId+"_txtArea";                         
9960     this.instanceId = instanceId;
9961     this.loader=function(){ 
9962         var fullnameValidB = F.extractValueB('fullname').liftB(checkCharLength);
9963         var messageValidB = F.extractValueB('message').liftB(checkCharLength);
9964         
9965         var emailBlurE = F.extractEventE('email', 'blur');
9966         var emailTextChangedB = F.extractValueB('email');
9967         var emailRequestB = emailBlurE.snapshotE(emailTextChangedB).mapE(function(text){
9968             return {email: ""+text};
9969         });
9970         var emailValidB = getAjaxRequestB(emailRequestB, scriptPath+"request/form_validator_check_email/").mapE(function(data){
9971             return data.valid;    
9972         }).startsWith(false);   
9973           
9974         var allFieldsValid = F.liftB(function(fullname, message, email){
9975             return fullname&&message&&email;
9976         }, fullnameValidB, messageValidB, emailValidB);
9977         
9978          var submitClickedE = F.extractEventE('submit', 'click').snapshotE(allFieldsValid).mapE(function(valid){
9979             if(valid)
9980                 alert("Submit clicked! All fields are valid!");
9981         });                
9982                                                                                              
9983         //Gui Reaction
9984         F.insertValueB(ifB(fullnameValidB, '#00FF00', '#FF0000'),'fullname', 'style', 'borderColor');
9985         F.insertValueB(ifB(messageValidB, '#00FF00', '#FF0000'),'message', 'style', 'borderColor');
9986         F.insertValueB(ifB(emailValidB, '#00FF00', '#FF0000'),'email', 'style', 'borderColor');
9987         F.insertValueB(ifB(emailValidB, scriptPath+'plugins/form_validator/tick.png', scriptPath+'plugins/form_validator/cross.png'),'emailTick', 'src')
9988         F.insertValueB(notB(allFieldsValid),'submit', 'disabled');
9989     }
9990     this.build=function(){
9991         return "<table><tr><td>Full Name:</td><td><input type=\"text\" alt=\"\" id=\"fullname\" /></td></tr><tr><td>Email Address:</td><td><input type=\"text\" alt=\"\" id=\"email\" /><img src=\"/resources/trans.png\" id=\"emailTick\" alt=\"\" style=\"vertical-align: middle;\" /></td></tr><tr><td>Message</td><td><textarea alt=\"\" id=\"message\" rows=\"6\" cols=\"45\"></textarea></td></tr><tr><td> </td><td><input type=\"submit\" value=\"Submit\" alt=\"\" id=\"submit\" /></td></tr></table>";
9992     }
9993 }                 
9994 
9995 /*function ValidatedContactFormConfigurator(){
9996     var id = "IntegerTableWidgetCont";
9997     this['load'] = function(newData){}
9998     this['build'] = function(newData){
9999         var targetName = (newData!=undefined&&newData['targetName']!=undefined)?newData['targetName']:"";
10000         return "Target Name: <input type=\"text\" id=\""+id+"\" value=\""+targetName+"\" />";  
10001     }
10002     this['getData'] = function(){
10003         return {"targetName": document.getElementById(id).value};
10004     }
10005     this['getName'] = function(){
10006         return "Integer TableWidget";
10007     }
10008     this['getDescription'] = function(){
10009         return "A one or two-dimensional table of integers. WIth controls to add, edit or delete data.";
10010     }
10011     this['getPackage'] = function(){
10012         return "Table";
10013     }
10014     //this['getImage'] = function(){
10015     //    var img = document.createElement("img");
10016     //    img.src = "plugins/aviat.csrDemo/table.png";
10017     //    img.alt = "";
10018     //    return img;
10019     //}
10020 }  */
10021 WIDGETS.register("ValidatedContactForm", ValidatedContactForm/*, ValidatedContactFormConfigurator*/);
10022 
10023 
10024 
10025 
10026 function GenderSelectionWidget(instanceId, data){   
10027     this.instanceId = instanceId;
10028     this.loader=function(){
10029         var valueName = (data.name==undefined)?"Checkbox":data.name;
10030         var formGroupB = DATA.get(data.formGroup, undefined, {}); 
10031         var genderB = F.mergeE(jQuery("#"+instanceId+"_male").fj('jQueryBind', 'change'), jQuery("#"+instanceId+"_female").fj('jQueryBind', 'change')).mapE(function(event){
10032             return (DOM.get(instanceId+"_male").checked)?"Male":"Female";
10033         }).startsWith(NOT_READY);
10034         var validB = genderB.liftB(function(gender){
10035             return gender!=NOT_READY;
10036         });
10037         var widgetValueB = F.liftB(function(valid, gender){
10038             if(!good()){
10039                 return NOT_READY;
10040             }
10041             //DOM.get(instanceId).className = ((valid)?'form_validator_validInput':'form_validator_invalidInput');
10042             return {valid: valid, value: gender, name: valueName};
10043         },validB, genderB);  
10044         
10045         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB);   
10046     }      
10047     this.build=function(){
10048         return "<span id=\""+instanceId+"\">Male: <input type=\"radio\" id=\""+this.instanceId+"_male\" name=\""+this.instanceId+"_radio\" /> Female: <input type=\"radio\" id=\""+this.instanceId+"_female\" name=\""+this.instanceId+"_radio\" /></span>";       
10049     }
10050 }
10051 WIDGETS.register("GenderSelectionWidget", GenderSelectionWidget);
10052 
10053 function CreditCardInputWidget(instanceId, data){   
10054     this.instanceId = instanceId;
10055     this.loader=function(){
10056         var valueName = (data.name==undefined)?"CardData":data.name;
10057         var formGroupB = DATA.get(data.formGroup, undefined, {}); 
10058 
10059         var cc1B = F.extractValueE(instanceId+"_cc1").startsWith(NOT_READY);       
10060         var cc1NumericB = cc1B.liftB(function(cc1){return jQuery.isNumeric(cc1);});
10061         var cc2B = F.extractValueE(instanceId+"_cc2").startsWith(NOT_READY);
10062         var cc2NumericB = cc2B.liftB(function(cc2){return jQuery.isNumeric(cc2);});
10063         var cc3B = F.extractValueE(instanceId+"_cc3").startsWith(NOT_READY);
10064         var cc3NumericB = cc3B.liftB(function(cc3){return jQuery.isNumeric(cc3);});
10065         var cc4B = F.extractValueE(instanceId+"_cc4").startsWith(NOT_READY);
10066         var cc4NumericB = cc4B.liftB(function(cc4){return jQuery.isNumeric(cc4);});
10067         
10068         F.insertValueB(F.ifB(cc1NumericB, 'form_validator_validInput', 'form_validator_invalidInput'),instanceId+"_cc1", 'className');
10069         F.insertValueB(F.ifB(cc2NumericB, 'form_validator_validInput', 'form_validator_invalidInput'),instanceId+"_cc2", 'className');
10070         F.insertValueB(F.ifB(cc3NumericB, 'form_validator_validInput', 'form_validator_invalidInput'),instanceId+"_cc3", 'className');
10071         F.insertValueB(F.ifB(cc4NumericB, 'form_validator_validInput', 'form_validator_invalidInput'),instanceId+"_cc4", 'className');
10072         
10073         var visaClickedB = F.extractEventE(instanceId+"_visa", "click").startsWith(NOT_READY);
10074         var masterCardClickedB = F.extractEventE(instanceId+"_mastercard", "click").startsWith(NOT_READY);
10075         var cardTypeB = F.liftB(function(visaClicked, masterCardClicked){
10076         	if(visaClicked==NOT_READY && masterCardClicked==NOT_READY){
10077         		return NOT_READY;
10078         	}
10079         	else if(visaClicked!=NOT_READY && masterCardClickedB==NOT_READY || visaClickedB.firedBefore(masterCardClickedB)){
10080         		return "Visa";
10081         	}
10082         	return "MasterCard";
10083         }, visaClickedB, masterCardClickedB);
10084         
10085         var expiryMonthB = F.extractValueE(instanceId+"_expiry_month").startsWith(NOT_READY);
10086         var expiryYearB = F.extractValueE(instanceId+"_expiry_year").startsWith(NOT_READY);
10087         
10088         var cscNumberB = F.extractValueE(instanceId+"_csc").startsWith(NOT_READY);
10089         var cscNumberValidB = cscNumberB.liftB(function(cscNumber){return jQuery.isNumeric(cscNumber);});
10090         F.insertValueB(F.ifB(cscNumberValidB, 'form_validator_validInput', 'form_validator_invalidInput'),instanceId+"_csc", 'className');
10091         
10092         var widgetValueB = F.liftB(function(cc1, cc2, cc3, cc4, cardType, expiryMonth, expiryYear, cscNumber){
10093         	if(!good()){
10094         		return NOT_READY;
10095         	}
10096         	var valid = (jQuery.isNumeric(cscNumber)) && (jQuery.isNumeric(expiryMonth)) && (jQuery.isNumeric(expiryYear)) && (jQuery.isNumeric(cc1)&&cc1.length==4) && (jQuery.isNumeric(cc2)&&cc2.length==4) && (jQuery.isNumeric(cc3)&&cc3.length==4) && (jQuery.isNumeric(cc4)&&cc4.length==4);
10097         	return {valid: valid, value: cardType+" "+cc1+cc2+cc3+cc4+" "+expiryMonth+"/"+expiryYear+" "+cscNumber, name: valueName};
10098         }, cc1B, cc2B, cc3B, cc4B, cardTypeB, expiryMonthB, expiryYearB, cscNumberB);
10099         
10100         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB);   
10101     }      
10102     var getSelectBoxRange = function(id, start, len, addFirstStr){
10103     	var html = "<select id=\""+id+"\">";
10104     	if(addFirstStr!=undefined){
10105     		html+="<option value=\""+addFirstStr+"\">"+addFirstStr+"</option>";
10106     	}
10107     	for(i=start;i<start+len;i++){
10108     		html+="<option value=\""+i+"\">"+i+"</option>";
10109     	}
10110     	html+="</select>";
10111     	return html;
10112     }
10113     this.build=function(){
10114         return "Card Type<br />" +
10115         		"Visa <input type=\"radio\" id=\""+instanceId+"_visa\" name=\""+instanceId+"_radio\" /><br />" +
10116         		"Mastercard <input type=\"radio\" id=\""+instanceId+"_mastercard\" name=\""+instanceId+"_radio\" /><br />" +
10117         		"<input id=\""+instanceId+"_cc1\" type=\"\" maxlength=\"4\" size=\"4\" /><input id=\""+instanceId+"_cc2\" type=\"\" maxlength=\"4\" size=\"4\" /><input id=\""+instanceId+"_cc3\" type=\"\" maxlength=\"4\" size=\"4\" /><input id=\""+instanceId+"_cc4\" type=\"\" maxlength=\"4\" size=\"4\" /><br />" +
10118         		"Expiry "+getSelectBoxRange(instanceId+"_expiry_month", 1, 12, "--")+"/"+getSelectBoxRange(instanceId+"_expiry_year", 2012, 5, "--")+"<br />" +
10119         		"CSC Number <input type=\"text\" id=\""+instanceId+"_csc\" size=\"5\" maxlength=\"5\" />";
10120     }
10121 }
10122 WIDGETS.register("CreditCardInputWidget", CreditCardInputWidget);
10123 
10124 
10125 
10126 /*Object {username: "Zysen", firstname: "Jay", lastname: "Shepherd", group_id: "3", email: "jay@zylex.net.nz"�}
10127 avatar: ""
10128 email: "jay@zylex.net.nz"
10129 firstname: "Jay"
10130 group_id: "3"
10131 lastname: "Shepherd"
10132 username: "Zysen"*/
10133 
10134 
10135 
10136 function ValidatedUserWidget(instanceId, data){
10137 	var id = instanceId+"_container";
10138 	var valueName = "user";
10139 	this.loader=function(){       
10140 		if(data.targetId!=undefined){
10141 			display = DOM.get(data.targetId).style.display;
10142 		}
10143         var formGroupB = DATA.get(data.formGroup, undefined, {});  
10144         var widgetValueB = F.liftB(function(user){
10145             if(!good()){
10146                 return NOT_READY;
10147             }
10148             if(data.targetId!=undefined){
10149             	DOM.get(data.targetId).style.display=(user.group_id==1)?'':'none';
10150             }
10151             return {valid: user.group_id!=1, value: "USER", name: valueName};
10152         },userB);  
10153         //pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB);  
10154     }      
10155     this.build=function(){
10156         return "<span id=\""+instanceId+"\"></span>";      
10157     }
10158 }
10159 WIDGETS.register("ValidatedUserWidget", ValidatedUserWidget);
10160 
10161 function UserFullNameInput(instanceId, data){
10162     this.instanceId = instanceId;
10163     this.inputId = instanceId+"_input"   
10164     var visible = (data.visible==undefined)?true:data.visible;
10165     this.loader=function(){       
10166         var formGroupB = DATA.get(data.formGroup, undefined, {});  
10167         var valueName = (data.name==undefined)?"SchoolName":data.name;
10168         
10169         
10170         var currentUserB = DATA.getRemote("aurora_current_user").behaviour;        
10171 
10172         var widgetValueB = currentUserB.liftB(function(user){
10173             if(!good()){
10174             	DOM.get(instanceId+"_input").className = 'form_validator_invalidInput';
10175                 return {valid: false, value: "", name: valueName};
10176             }
10177             
10178             DOM.get(instanceId+"_input").className = 'form_validator_validInput';
10179             DOM.get(instanceId+"_input").value = user.firstname+" "+user.lastname;
10180             return {valid: true, value: user.firstname+" "+user.lastname, name: valueName};
10181         });  
10182         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB);  
10183     }      
10184     this.build=function(){
10185         return "<input id=\""+instanceId+"_input\" type=\""+(visible?'text':'hidden')+"\" />";//"<input id=\""+this.inputId+"\" type=\"text\">";         
10186     }
10187 }
10188 WIDGETS.register("UserFullNameInput", UserFullNameInput);
10189 
10190 function UserEmailInput(instanceId, data){
10191     this.instanceId = instanceId;
10192     this.inputId = instanceId+"_input"   
10193     var visible = (data.visible==undefined)?true:data.visible;
10194     this.loader=function(){       
10195         var formGroupB = DATA.get(data.formGroup, undefined, {});  
10196         var valueName = (data.name==undefined)?"SchoolName":data.name;
10197         
10198         
10199         var currentUserB = DATA.getRemote("aurora_current_user").behaviour;        
10200 
10201         var widgetValueB = currentUserB.liftB(function(user){
10202             if(!good()){
10203             	DOM.get(instanceId+"_input").className = 'form_validator_invalidInput';
10204                 return {valid: false, value: "", name: valueName};
10205             }
10206             
10207             DOM.get(instanceId+"_input").className = 'form_validator_validInput';
10208             DOM.get(instanceId+"_input").value = user.email;
10209             return {valid: true, value: user.email, name: valueName};
10210         });  
10211         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB);  
10212     }      
10213     this.build=function(){
10214         return "<input id=\""+instanceId+"_input\" type=\""+(visible?'text':'hidden')+"\" />";//"<input id=\""+this.inputId+"\" type=\"text\">";         
10215     }
10216 }
10217 WIDGETS.register("UserEmailInput", UserEmailInput);
10218 function GoogleMapWidget(instanceId, data){
10219     var mapId = instanceId+"_map";
10220     var zoom = parseInt(data.zoom);
10221     this.zoomChangedE = F.receiverE();
10222     this.centerChangedE = F.receiverE();
10223     var parent = this;
10224     this.loader=function(addressB){
10225         //var scriptLoadedE = loadScriptE("http://maps.googleapis.com/maps/api/js?key=AIzaSyCP1Ej3uTUHUBkzi4Q6F4vujwyWd3ocVNA&sensor=false");
10226         var addressB = (addressB==undefined)?(data.address!=undefined?F.constantB(data.address):F.constantB({lat: data.lat, lng: data.lng})):addressB;
10227         var mapB = F.oneE().startsWith(NOT_READY).liftB(function(data){
10228             if(!good())
10229                 return NOT_READY;
10230             var map = new google.maps.Map(DOM.get(mapId), {zoom: zoom, mapTypeId: google.maps.MapTypeId.ROADMAP});
10231             var marker = new google.maps.Marker({
10232 			    position: map.getCenter(),
10233 			    map: map,
10234 			    title: 'Click to zoom'
10235 			  });
10236             google.maps.event.addListener(map, 'zoom_changed', function() {
10237 				parent.zoomChangedE.sendEvent(map.getZoom());
10238 			});
10239 			
10240 			google.maps.event.addListener(map, 'center_changed', function() {
10241 				parent.centerChangedE.sendEvent(map.getCenter().toString());
10242 			});
10243 			
10244 			
10245             return map;
10246         });
10247         var locationB = geoCodeB(addressB);
10248         F.liftB(function(map, geocode){
10249             if(!good())
10250                 return NOT_READY;
10251            if(geocode.results.length>0){
10252                if(DOM.get(mapId).style.display=='none'){
10253                     DOM.get(mapId).style.display = 'inline-block'; 
10254                }
10255                log(geocode.results[0].geometry.location.toString());
10256                
10257                
10258                map.panTo(geocode.results[0].geometry.location, zoom);
10259            }
10260            else if(geocode.results.lat){
10261            		map.panTo(new LatLng(geocode.results.lat, geocode.results.lng), zoom);
10262            }
10263            else{
10264            		map.panTo(new LatLng(-41.2864603, 174.77623600000004), zoom);
10265            }
10266         }, mapB, locationB);                
10267     }
10268     this.build=function(){   
10269         
10270         var d = (data.placeholder==undefined)?undefined:getPlaceholderDimensions(data.placeholder);
10271         var width = (data.placeholder==undefined)?"100%":d.width+d.wUnit;
10272         var height = (data.placeholder==undefined)?"300px":d.height+d.hUnit;
10273         return "<span id=\""+mapId+"\" style=\"margin: 0 auto; display: none; width: "+width+"; height: "+height+";\"> </span>";
10274     }
10275     this.destroy=function(){
10276     }
10277 }
10278 function GoogleMapWidgetConfigurator(){
10279 	var instanceId = "GoogleMapWidget1";
10280 	var exampleWidget = new GoogleMapWidget(instanceId, {zoom: 10});//placeholder: mapContainer, 
10281     var addressId = "addressId";
10282     var parent = this;
10283     this['load'] = function(newData){
10284     	var addressB = F.extractValueB(addressId, 'innerHTML').calmB(1000);//F.constantB("26 manuka st, stokes valley, lower hutt")
10285     	exampleWidget.loader(addressB);
10286     	parent.zoomChangedB = exampleWidget.zoomChangedE.startsWith(10);
10287     	parent.centerChangedB = exampleWidget.centerChangedE.startsWith({x: -41.2864603, y:174.77623600000004});
10288     }
10289     this['build'] = function(newData){
10290     	var address = (newData!=undefined&&newData['address']!=undefined)?newData['address']:"";
10291         var zoom = (newData!=undefined&&newData['zoom']!=undefined)?newData['zoom']:"2";
10292     	return "<h2>Google Map Widget</h2>"+exampleWidget.build()+
10293         "<textarea type=\"text\" id=\""+addressId+"\" value=\""+address+"\" rows=\"8\" cols=\"80\">Wellington</textarea>"; 
10294     }
10295     this['getData'] = function(){
10296     	var location = parent.centerChangedB.valueNow().replace('(', '').replace(')', '').replace(' ', '').split(',');
10297         return {lat: location[0], lng: location[1],"zoom":parent.zoomChangedB.valueNow()};
10298     }
10299     this['getName'] = function(){
10300         return "Google Map";
10301     }
10302     this['getDescription'] = function(){
10303         return "GOogle Map";
10304     }
10305     this['getPackage'] = function(){
10306         return "Google";
10307     }
10308 }  
10309 
10310 function GoogleStreetViewWidget(instanceId, data){
10311     var mapId = instanceId+"_map";
10312     var geocoder = new google.maps.Geocoder();
10313     this.loader=function(){
10314        var pin = new google.maps.MVCObject();
10315         var address = data.address;
10316         var zoom = parseInt(data.zoom);
10317         var pitch = parseInt(data.pitch);
10318         var heading = parseInt(data.heading);
10319         geocoder.geocode( { 'address': address}, function(results, status) {
10320       if (status == google.maps.GeocoderStatus.OK) {
10321       
10322         panorama = new google.maps.StreetViewPanorama(document.getElementById(mapId), {
10323        //navigationControl: false,
10324        enableCloseButton: false,
10325        addressControl: false,
10326        linksControl: false,
10327        visible: true,
10328        pov: {heading:heading,pitch:pitch,zoom:zoom},
10329        position: results[0].geometry.location
10330       });
10331       
10332       } else {
10333         alert("Geocode was not successful for the following reason: " + status);
10334       }
10335     });              
10336     }
10337     this.build=function(){
10338        /* return "<div style=\"width: "+data.placeholder.style.width+"; height: "+data.placeholder.style.height+";\" class=\"googleMapSVSurround\"><div id=\""+mapId+"\" class=\"map_canvas\"></div></div>";              */
10339        return "<div id=\""+mapId+"\" style=\"width: 400px; height: 400px;\">MAP</div>";
10340     }
10341     this.destroy=function(){
10342     }
10343 }  
10344 /**
10345  *  IntegerTableWidgetConfigurator
10346  * @constructor
10347  */
10348 function GoogleStreetViewWidgetConfigurator(){
10349     var addressId = "addressId";
10350     var headingId = "headingId";
10351     var pitchId = "pitchId";
10352     var zoomId = "zoomId";
10353     this['load'] = function(newData){}
10354     this['build'] = function(newData){
10355         var address = (newData!=undefined&&newData['address']!=undefined)?newData['address']:"";
10356         var heading = (newData!=undefined&&newData['heading']!=undefined)?newData['heading']:"0";
10357         var pitch = (newData!=undefined&&newData['pitch']!=undefined)?newData['pitch']:"0";
10358         var zoom = (newData!=undefined&&newData['zoom']!=undefined)?newData['zoom']:"2";
10359         return "Address: <input type=\"text\" id=\""+addressId+"\" value=\""+address+"\" /><br />"+
10360         "Heading: <input type=\"text\" id=\""+headingId+"\" value=\""+heading+"\" /><br />"+
10361         "Pitch: <input type=\"text\" id=\""+pitchId+"\" value=\""+pitch+"\" /><br />"+
10362         "Zoom: <input type=\"text\" id=\""+zoomId+"\" value=\""+zoom+"\" /><br />";  
10363     }
10364     this['getData'] = function(){
10365         return {"address": document.getElementById(addressId).value, "heading":document.getElementById(headingId).value, "pitch":document.getElementById(pitchId).value, "zoom":document.getElementById(zoomId).value};
10366     }
10367     this['getName'] = function(){
10368         return "Google Street View";
10369     }
10370     this['getDescription'] = function(){
10371         return "Street View";
10372     }
10373     this['getPackage'] = function(){
10374         return "Google";
10375     }
10376 }         
10377 WIDGETS.register("googleMapWidget", GoogleMapWidget, GoogleMapWidgetConfigurator);
10378 WIDGETS.register("googleStreetViewWidget", GoogleStreetViewWidget, GoogleStreetViewWidgetConfigurator);                
10379 
10380 
10381 
10382 function geoCodeB(addressB){
10383     var rec = F.receiverE();
10384     addressB.liftB(function(address){  
10385         if(!good())
10386             return NOT_READY;
10387         log("Geocoding: "+address);
10388         if(typeof(address)=='string'){
10389 	        var geocoder = new google.maps.Geocoder();
10390 	        geocoder.geocode( { 'address': address}, function(results, status) {
10391 	            log(status);
10392 	            log(results);
10393 	            rec.sendEvent({results: results, status: status});
10394 	        });
10395         }
10396         else{
10397         	rec.sendEvent({results: address, status: 1});
10398         }
10399     });
10400     
10401     return rec.startsWith(NOT_READY); 
10402 }
10403 
10404 function ImageWidget(instanceId, data, galleryD, galleryB){
10405     allWidgets[instanceId] = this;
10406     this.deleteE = receiverE();
10407     var imageId = instanceId+"_img";
10408     var img = document.createElement('img');    
10409     
10410     this.loader=function(){
10411         this.deleteE.snapshotE(galleryB).mapE(function(galleries){
10412             for(index in galleries){                                                                                                                                                                                    
10413                 for(imageId in galleries[index].images){
10414                     if(galleries[index].images[imageId].upload_id==data.upload_id){
10415                         galleries[index].images[imageId].deleted=true;
10416                         galleryD.set(galleries);
10417                         return;
10418                     } 
10419                 }
10420             }
10421 
10422         });
10423         if(data.rights)
10424             jQuery(img).contextmenu({'menu':{'Delete':'javascript:allWidgets[\''+instanceId+'\'].deleteE.sendEvent(true);'}});
10425         if(data.fadeIn!=undefined){
10426             //var imgLoadedE = extractEventE(img, 'load');
10427             //var imageFadedE = jFadeInE(imgLoadedE, imageId, data.fadeIn);
10428             jQuery(document.getElementById(imageId)).fadeIn(data.fadeIn, function(){});
10429         }//fadeInE(getElement(imageId));
10430     }
10431     this.build=function(){
10432         img.id = imageId;
10433         //img.style.display=(data.fadeIn!=undefined)?'none':'block';
10434         img.src = (data.src!=undefined)?data.src:data.placeholder.src;
10435         
10436         img.width = (data.width!=undefined)?data.width:data.placeholder.style.width.replace('px', '');
10437         img.height = (data.height!=undefined)?data.height:data.placeholder.style.height.replace('px', '');
10438         
10439         var anchor = document.createElement('a');
10440         anchor.className = data.className;
10441         anchor.href=SETTINGS.scriptPath+"content/imagegallery/"+data.upload_id+"_medium"; 
10442         anchor.appendChild(img);
10443         return anchor;
10444     }
10445     this.destroy=function(){
10446         allWidgets[instanceId] = null;
10447         delete allWidgets[instanceId];
10448     }
10449 }
10450 function ImageGalleryWidget(instanceId,data){
10451     var dragHere = document.createElement('div');
10452                     dragHere.innerHTML = "Empty Gallery<br />Drag Images Here";
10453                     dragHere.className = "imageGallery_fileDragBox";
10454                     
10455     var width = (data.placeholder==null)?data.width:data.placeholder.style.width.replace('px', '');
10456     var height = (data.placeholder==null)?data.height:data.placeholder.style.height.replace('px', '');
10457     var widgets = new Array();
10458     var widgetId = instanceId+"_MAIN";
10459     var tableDivId = instanceId+"_table";
10460     var parent = this;
10461     this.loader=function(){
10462         
10463         var dragDropW = new FileUploaderDragDropWidget(instanceId+"_dragDrop", {targetId:widgetId});
10464         //if(imagegalleryRights)
10465             dragDropW.loader();
10466         
10467         var uploadCompleteE = dragDropW.uploadCompleteE();
10468         var galleriesD = DATA.getRemote("imageGallery_galleryList", data.gallery);
10469         var galleriesB = galleriesD.event.startsWith(null);
10470         var renderHTMLGalleriesB = galleriesB.liftB(function(galleries){
10471             parent.destroyChildWidgets();
10472             if(galleries==null)
10473                 return "";//show loading or something.
10474             widgets = new Array();
10475             widgets.length=0;
10476             var galleriesDiv = document.createElement('div');
10477             for(index in galleries){                                                                                                                                                       
10478                 var gallery = galleries[index];
10479                 var galleryDiv = document.createElement('div');
10480                 galleryDiv.appendChild(dragHere);
10481                 var galleryId = instanceId+"_"+gallery.galleryId;
10482                 galleryDiv.id = galleryId;
10483                 galleryDiv.className = 'imageGallery_gallery';                
10484                 var gallery = galleries[index];                                          
10485                 for(imageId in gallery.images){
10486                     var image = gallery.images[imageId];
10487                     if(image.deleted)
10488                         continue;
10489                     image.src = SETTINGS.scriptPath+'content/imagegallery/'+image.upload_id+"_small";
10490                     var newImage = new ImageWidget(instanceId+"_"+imageId, {src:image.src, width: data.thumbWidth, height: data.thumbHeight, fadeIn:500, rights: image.rights, upload_id: image.upload_id, className: "galleryLink"}, galleriesD, galleriesB);
10491                     widgets.push(newImage);
10492                     var rar = newImage.build();
10493                     galleryDiv.appendChild(rar);
10494                 }
10495                 
10496                 if(gallery.images.length==0)
10497                     dragHere.style.display = 'block';    
10498                 else
10499                     dragHere.style.display = 'none'; 
10500                 galleriesDiv.appendChild(galleryDiv);
10501                 break;
10502             }
10503             return galleriesDiv;               
10504         });
10505         F.insertDomB(renderHTMLGalleriesB, tableDivId);
10506         uploadCompleteE.snapshotE(liftB(function(uploadData, galleries){if(uploadData==null||galleries==null)return null;return {uploadData:uploadData, galleries:galleries};},uploadCompleteE.startsWith(null), galleriesB)).mapE(function(data){
10507             var gallery = data.galleries[0];
10508             var uploadData = data.uploadData;
10509             gallery.images[gallery.images.length] = {upload_id: data.uploadData.files[0].id, caption: "", rights: true};
10510             galleriesD.set(data.galleries);   
10511         });
10512         renderHTMLGalleriesB.liftB(function(x){if(x!=""){parent.loadChildWidgets();jQuery('a.galleryLink').lightBox();}/*parent.inflateEditorAreas();*/});
10513     }
10514     this.destroyChildWidgets = function(){
10515         for(index in widgets)
10516             widgets[index].destroy();
10517         widgets = new Array();
10518     }
10519     this.loadChildWidgets = function(){
10520         for(index in widgets){
10521             widgets[index].loader();
10522         }
10523     }
10524     this.destroy=function(){
10525         this.destroyChildWidgets();
10526         database.deregister("aurora_settings", data.plugin);
10527     }
10528     this.build=function(){
10529         return "<div id=\""+widgetId+"\" style=\"display: block; width: "+width+"px; height: "+height+"px;\" ><div id=\""+tableDivId+"\"></div></div>";
10530     }
10531 }
10532 WIDGETS.register("imageWidget", ImageWidget);
10533 WIDGETS.register("imageGallery", ImageGalleryWidget);
10534 
10535 /*function UploadableImageWidget(instanceId, data){    
10536 	var width = data.placeholder.getAttribute("width");
10537     width=(width==null?data.placeholder.style.width.replace('px', ''):width);
10538 	var height = data.placeholder.getAttribute("height");
10539 	height=(height==null?data.placeholder.style.height.replace('px', ''):height);
10540     this.imageLoadE = F.receiverE();
10541     
10542     var parent = this;
10543     data.acceptedTypes = ["image/jpg", "image/jpeg", "image/png", "image/gif"];
10544     data.targetId = instanceId+"_container";
10545     
10546     var uploadWidget = new FileUploaderDragDropWidget(instanceId+"_dnd",data);   
10547                          
10548     this.loader=function(widgetRefB){
10549     	DOM.get(instanceId+"_img").onload = function(event){
10550         	DOM.get(instanceId+"_container").style.width = DOM.get(instanceId+"_img").clientWidth+"px";
10551         	DOM.get(instanceId+"_container").style.height = DOM.get(instanceId+"_img").clientHeight+"px";
10552         	parent.imageLoadE.sendEvent(DOM.get(instanceId+"_img"));
10553         }
10554     	uploadWidget.loader();
10555         var thumbPathB = widgetRefB.liftB(function(widgetRef){
10556             if(!good())
10557                 return NOT_READY;
10558             return window['SETTINGS']['scriptPath']+"resources/upload/public/imagegallery/thumbs/"+widgetRef+".png";
10559         });
10560         var imageExistsB = thumbPathB.liftB(function(imagePath){
10561         	var imageFrame = DOM.get(instanceId+"_img");
10562         	if(!good())
10563                 return NOT_READY;
10564         	imageFrame.style.display = 'none';
10565             imageFrame.src = imagePath+"?time="+(new Date()).getTime();
10566             return UrlExists(imagePath);
10567         });
10568         
10569         imageExistsB.liftB(function(imageExists){
10570             if(!good())
10571                 return NOT_READY;
10572             var dropZone = (!imageExists)?uploadWidget.getDropZone().outerHTML:uploadWidget.getPanel().outerHTML;
10573             DOM.get(instanceId+"_dz").innerHTML = dropZone;
10574             if(imageExists){
10575                 DOM.get(uploadWidget.getPanel().id).innerHTML = "";
10576             }                                  
10577             
10578         });
10579         
10580         uploadWidget.sendProgressE.mapE(function(progress){
10581         	jQuery(DOM.get(instanceId+"_progress")).progressbar({value: Math.ceil(progress.queuePercentageComplete)});
10582         });
10583         
10584         var uploadCompleteB = uploadWidget.uploadCompleteE.mapE(function(response){
10585             return {path: response.path, width: width, height: height}; 
10586         }).startsWith(NOT_READY);
10587         
10588         var processRequestB = F.liftB(function(request, widgetRef){                                                                                                    
10589             if(!good())
10590                 return NOT_READY;
10591             request.id = widgetRef;
10592             return request;
10593         }, uploadCompleteB, widgetRefB);
10594             
10595         var imageProcessedE = getAjaxRequestB(processRequestB, window['SETTINGS']['scriptPath']+"/request/IG_processImage").mapE(function(ret){
10596             if(ret==NOT_READY)
10597                 return NOT_READY;
10598             var container = DOM.get(instanceId+"_container");
10599             var image = DOM.get(instanceId+"_img");
10600             log(image.clientWidth+" "+image.clientHeight);
10601             var progress = DOM.get(instanceId+"_progress"); 
10602             jQuery(DOM.get(instanceId+"_progress")).progressbar("destroy");
10603             //progress.innerHTML = uploadWidget.getPanel().outerHTML;
10604             image.src = ret.path+"?time="+(new Date()).getTime();
10605             DOM.get(uploadWidget.getPanel().id).innerHTML = "";
10606         });                                                                 
10607     }      
10608     this.hide = function(){
10609         DOM.get(instanceId+"_container").style.display = 'none';
10610     }              
10611     this.show = function(){
10612         DOM.get(instanceId+"_container").style.display = 'block';
10613     }                                
10614     this.build=function(){
10615         log("School Logo Widget BUILD");
10616     	return "<div id=\""+instanceId+"_container\" style=\"margin: 0 auto; text-align: center; width: "+width+"px; height: "+height+"px;\">"+DOM.createImg(instanceId+"_img", "UploadableImageWidget", "/resources/trans.png").outerHTML+"<div id=\""+instanceId+"_dz\"></div><div id=\""+instanceId+"_progress\"></div></div>";   
10617     }
10618     this.destroy=function(){
10619         uploadWidget.destroy();
10620     }
10621     
10622 }*/
10623 
10624 
10625 
10626 
10627 function UploadableImageWidget(instanceId, data){  
10628 	var UPLOAD = new AuroraUploadManager(data); 
10629 	var parent = this;
10630 	var acceptedTypes = ["image/jpg", "image/jpeg", "image/png", "image/gif"];
10631 	//Configure Dimensions 
10632 	
10633 	var dropHtml = data.dropHtml;
10634 	var dropHoverHtml = data.dropHoverHtml;
10635 	
10636 	var width = data.placeholder.getAttribute("width");
10637     width=(width==null?data.placeholder.style.width.replace('px', ''):width);
10638 	var height = data.placeholder.getAttribute("height");
10639 	height=(height==null?data.placeholder.style.height.replace('px', ''):height);
10640 	
10641     this.loader=function(widgetRefB){
10642     	widgetRefB = widgetRefB==undefined?F.constantB(data.widgetRef):widgetRefB;
10643     	var imageZone = DOM.get(instanceId+"_imagezone");
10644     	var imageElement = DOM.get(instanceId+"_imagezone");
10645     	parent.dropE = F.mergeE(F.extractEventE(imageZone, 'drop'), F.extractEventE(imageElement, 'dragenter')).cancelDOMBubbleE();
10646         parent.dragOverE = F.mergeE(F.extractEventE(imageZone, 'dragover'), F.extractEventE(imageElement, 'dragenter')).cancelDOMBubbleE().mapE(function(event){
10647         	event.dataTransfer.dropEffect = 'move';
10648             if(imageZone.innerHTML==dropHtml){
10649             	imageZone.innerHTML = dropHoverHtml;
10650             }
10651             return event;
10652         });
10653         
10654         parent.dragEnterE = F.mergeE(F.extractEventE(imageZone, 'dragenter'), F.extractEventE(imageElement, 'dragenter')).mapE(function(event){
10655         	if(imageZone.innerHTML==dropHtml){
10656         		imageZone.innerHTML = dropHoverHtml;
10657         	}
10658             return event;
10659         });
10660         
10661         parent.dragExitE = F.mergeE(F.extractEventE(imageZone, 'dragleave'), F.extractEventE(imageElement, 'dragenter')).mapE(function(event){
10662         	if(imageZone.innerHTML==dropHoverHtml){
10663         		imageZone.innerHTML = dropHtml;
10664         	}
10665             return event;
10666         });     
10667         parent.dragExitE = F.mergeE(F.extractEventE(imageZone, 'dragend'), F.extractEventE(imageElement, 'dragenter')).mapE(function(event){
10668         	if(imageZone.innerHTML==dropHoverHtml){
10669         		imageZone.innerHTML = dropHtml;
10670         	}
10671             return event;
10672         });
10673     
10674         parent.filesDropE = parent.dropE.filterE(function(event){
10675         	var files = event.target.files || event.dataTransfer.files; 
10676         	if(files!=undefined && files.length>1){
10677         		UI.showMessage("Upload Error", "Unable to process multiple images, please upload a single image.");
10678         		return false;
10679             }
10680         	return files!=undefined;
10681         	
10682         }).mapE(function(event){ 
10683         	var files = event.target.files || event.dataTransfer.files;  
10684             var totalBytes = 0;
10685             var fileArray = [];
10686             if(files[0]!=undefined && files[0].size!=undefined){
10687                 if(files[0].type!="" && arrayContains(acceptedTypes, files[0].type)){
10688                     totalBytes=files[0].size;
10689                     UPLOAD.add(files[0]);
10690                 }
10691                 else{
10692                     log("Unable to upload directories skipping "+files[0].type);
10693                 }
10694             }
10695             return {size: totalBytes, files:files};
10696         }).filterE(function(fileData){
10697         	return fileData.size>0;
10698         });
10699         parent.uploadCompleteE = UPLOAD.uploadCompleteE;
10700         parent.allUploadsCompleteE = UPLOAD.allUploadsCompleteE;
10701               
10702         var sendProgressE = UPLOAD.progressUpdateB.changes().filterE(function(val){return val!=NOT_READY;}).mapE(function(progress){              
10703                var total = progress.total;
10704                var loaded = progress.loaded;
10705                var queuePercentage = (loaded/total)*100; 
10706                queuePercentage = queuePercentage<0?0:(queuePercentage>100?100:queuePercentage); 
10707                DOM.get(instanceId+"_status").innerHTML = "Uploading "+Math.ceil(queuePercentage)+"%";
10708                jQuery(DOM.get(instanceId+"_progress")).progressbar({value: Math.ceil(queuePercentage)});
10709                return {filePercentageComplete:queuePercentage, queuePercentageComplete:queuePercentage,currentFile:progress.currentFile, rate:progress.rate, queue:progress.queue, formattedTotal:progress.formattedTotal}; 
10710         });     
10711         
10712         var thumbPathB=widgetRefB.liftB(function(ref){log(ref);if(!good()){return NOT_READY;}return window['SETTINGS']['scriptPath']+"resources/upload/public/imagegallery/thumbs/"+ref+".png";});
10713         
10714         imageElement.onload = function(){
10715         	imageElement.style.width = imageElement.clientWidth+"px";
10716         	imageElement.style.height = imageElement.clientHeight+"px";
10717         }
10718         
10719         var imageExistsB = thumbPathB.liftB(function(imagePath){
10720         	if(!good())
10721                 return NOT_READY;
10722             if(UrlExists(imagePath)){
10723             	DOM.get(instanceId+"_img").src = imagePath+"?time="+(new Date()).getTime();
10724             	return true;
10725             }
10726             else if(dropHtml!=undefined){
10727             	DOM.get(instanceId+"_imagezone").innerHTML = dropHtml;
10728             }
10729             else{
10730             	DOM.get(instanceId+"_imagezone").innerHTML = "<div style=\"width:"+width+"px;height:"+height+"px\">Drop an image here</div>";
10731             }
10732             return false;
10733         });
10734         
10735         var processRequestB = F.liftB(function(uploadRequest, ref){                                                                                                    
10736             if(!good())
10737                 return NOT_READY;
10738             return {id: ref, path: uploadRequest.path, width: width, height: height};
10739         }, parent.uploadCompleteE.filterE(function(res){
10740         	if(res.status==NO_PERMISSION){
10741         		log("Permission Error, You do not have permission to upload to this path");
10742         		UI.showMessage("Permission Error","You do not have permission to upload to this path");
10743         	}
10744         	return res.status==1;}).startsWith(NOT_READY), widgetRefB);
10745             
10746         var imageProcessedE = getAjaxRequestB(processRequestB, window['SETTINGS']['scriptPath']+"/request/IG_processImage").mapE(function(ret){
10747             if(ret==NOT_READY)
10748                 return NOT_READY;
10749             DOM.get(instanceId+"_imagezone").innerHTML = "<img src=\""+ret.path+"?time="+(new Date()).getTime()+"\" alt=\"\" />";
10750             DOM.get(instanceId+"_status").innerHTML = "";
10751             jQuery(DOM.get(instanceId+"_progress")).progressbar("destroy");
10752         });                                                                 
10753     }      
10754     this.hide = function(){
10755         DOM.get(instanceId+"_container").style.display = 'none';
10756     }              
10757     this.show = function(){
10758         DOM.get(instanceId+"_container").style.display = 'block';
10759     }                                
10760     this.build=function(){
10761     	return "<div id=\""+instanceId+"_container\" style=\"margin: 0 auto; width: "+width+"px;\"><div id=\""+instanceId+"_imagezone\"><img id=\""+instanceId+"_img\" alt=\"\" /></div><div id=\""+instanceId+"_progress\"></div><div id=\""+instanceId+"_status\" style=\"position: relative; top: -25px;\" class=\"imageGallery_status\"></div></div>";   
10762     }
10763     this.destroy=function(){
10764 
10765     }
10766 }
10767 
10768 
10769 
10770 
10771 
10772 function UploadableImageWidgetConfigurator(){
10773     this['requiresRef'] = true;
10774 	this['load'] = function(newData){}
10775     this['build'] = function(newData){}
10776     this['getData'] = function(){}
10777     this['getName'] = function(){
10778         return "Image Uploader Widget";
10779     }
10780     this['getDescription'] = function(){
10781         return "A blank image which can be changed using drag and drop";
10782     }
10783     this['getPackage'] = function(){
10784         return "Image Gallery";
10785     }
10786 } 
10787 WIDGETS.register("UploadableImageWidget", UploadableImageWidget, UploadableImageWidgetConfigurator);
10788 
10789 
10790 (function ($, flapjax) {
10791     var methods = {
10792         'clicksE': function () {
10793             if (!(this instanceof $)) { return; }
10794             var events = [];
10795 
10796             var i;
10797             for (i = 0; i < this.length; i += 1) {
10798                 var elm = this[i];
10799                 events.push(flapjax.clicksE(elm));
10800             }
10801 
10802             return flapjax.mergeE.apply({}, events);
10803         },
10804         'extEvtE': function (eventName) {
10805             if (!(this instanceof $)) { return; }
10806             var events = [];
10807 
10808             var i;
10809             for (i = 0; i < this.length; i += 1) {
10810                 var elm = this[i];
10811                 events.push(flapjax.extractEventE(elm, eventName));
10812             }
10813 
10814             return flapjax.mergeE.apply({}, events);
10815         },
10816         'extValB': function () {
10817             if (!(this instanceof $) || this.length < 1) { return; }
10818             return flapjax.extractValueB(this.get(0));
10819         },
10820         'extValE': function () {  
10821             if (!(this instanceof $)) { return; }
10822             var events = [];
10823 
10824             var i;
10825             for (i = 0; i < this.length; i += 1) {
10826                 var elm = this[i]; 
10827                 events.push(flapjax.extractValueE(elm));
10828             }
10829 
10830             return flapjax.mergeE.apply({}, events);
10831         },
10832         'jQueryBind': function (eventName) {       
10833             if (!(this instanceof $)) { return; }
10834             var eventStream = F.receiverE();
10835             //alert('Binding to: '+eventName);
10836             this.bind(eventName, function (e) {
10837                //alert('BIND');
10838                 eventStream.sendEvent(arguments.length > 1 ? arguments : e);
10839             });
10840             
10841             return eventStream;
10842         },
10843         'liftB': function (fn) {
10844             if (!(this instanceof $) || this.length < 1) { return; }
10845             return this.fj('extValB').liftB(fn);
10846         },
10847         'liftBArr': function (fn) {
10848             return this.map(function () {
10849                 return flapjax.extractValueB(this).liftB(fn);
10850             });
10851         }
10852     };
10853 
10854     jQuery.fn.fj = function (method) {
10855         var args = Array.prototype.slice.call(arguments, 1);
10856         return methods[method].apply(this, args);
10857     };
10858 })(jQuery, F);
10859 
10860 
10861 
10862 //Example usage: <img src="/resources/noWidget.png" alt="{[{id: '1', text: 'Bla'}, {id: '2', text: 'Yo ho'}]}" class="widget_PayPalOptionButton" />
10863 
10864 function PayPalOptionButton(instanceId, data){
10865 	var paypalUrl = (data.sandboxMode!=undefined&&(data.sandboxMode==true||data.sandboxMode=="true"))?"https://www.sandbox.paypal.com/cgi-bin/webscr":"https://www.paypal.com/cgi-bin/webscr";
10866 	var productId = data.productId;
10867     var products = data.products;
10868     var buttonText = (data.buttonText!=undefined)?data.buttonText:"Purchase";
10869     //var products = [{id: 2, text: "Bla"}, {id: 2, text: "Bla"}];
10870     
10871     var autoSubmit = (data.autoSubmit!=undefined)?data.autoSubmit:true;
10872     var showButton = (data.showButton!=undefined)?data.showButton:true;
10873     this.invoiceE = undefined;
10874     var requestInvoiceE = F.receiverE();
10875     this.loader=function(){
10876     	var quantityB = DOM.get(instanceId+"_quantity")==undefined?F.constantB(1):F.extractValueE(instanceId+"_quantity").startsWith(1);
10877     	var productSelectedB = F.extractValueE(instanceId+"_products").startsWith(DOM.get(instanceId+"_products").value);
10878 		
10879 		productSelectedB.liftB(function(productSelected){
10880 			jQuery("."+instanceId+"_options").hide();
10881 			jQuery("#"+instanceId+"_"+productSelected).show();
10882 		});
10883 		
10884 		
10885 		var paypalHTMLVariablesB = F.liftB(function(optionSelected, quantity){
10886 			return {productId: optionSelected, quantity: quantity};
10887 		}, productSelectedB, quantityB);
10888     	var buttonClickedE = F.extractEventE(instanceId+"_button", "click").snapshotE(paypalHTMLVariablesB).mapE(function(variables){
10889         	DOM.get(instanceId+"_productId").value = variables.productId;	
10890         	DOM.get(instanceId+"_quantityField").value = variables.quantity;	
10891         	
10892         	for(var index in products){
10893     			var product = products[index];
10894     			if(product.id==variables.productId&&product.optionName!=undefined&&product.options!=undefined){
10895     				DOM.get(instanceId+"_form").innerHTML+="<input type='hidden' name='on0' value='"+product.optionName+"' /><input type='hidden' name='os0' value='"+DOM.get(instanceId+"_"+variables.productId).value+"' />";	
10896     			}
10897     		}
10898     		
10899         	return {};
10900         });   
10901         this.invoiceE = getAjaxRequestE(F.mergeE(requestInvoiceE, buttonClickedE.mapE(function(){return true;})), "/request/products_createInvoice").mapE(function(invoice){
10902         	DOM.get(instanceId+"_form").innerHTML+="<input type='hidden' name='invoice' value='"+invoice.invoiceId+"' />";
10903         	if(autoSubmit){
10904         		//log(DOM.get(instanceId+"_form"));
10905         		DOM.get(instanceId+"_form").submit();
10906         	}
10907         	return invoice;
10908         });  
10909     }
10910     this.setOptionValue = function(value){
10911     	DOM.get(instanceId+"_option").value = value;
10912     };
10913     this.requestInvoice = function(option){
10914     	requestInvoiceE.sendEvent((option==undefined?true:option));
10915     };
10916     this.getForm = function(){
10917     	return DOM.get(instanceId+"_form");
10918     };
10919     this.submit = function(){
10920     	DOM.get(instanceId+"_form").submit();
10921     	/*this.requestInvoice();
10922     	autoSubmit = true;*/
10923     }
10924     this.build=function(){
10925     	var quantity = "  <span class=\"payPal_quantityField\">Quantity: <select id=\""+instanceId+"_quantity\">";
10926     	if((data.showQuantity!=undefined&&data.showQuantity)||(data.maxQuantity!=undefined)){
10927 	    	var maxQuantity = (data.maxQuantity!=undefined&&typeof(data.maxQuantity)=='number'?data.maxQuantity:50)
10928 	    	for(var i=1;i<=maxQuantity;i++){
10929 	    		 quantity+="<option value=\""+i+"\">"+i+"</option>";
10930 	    	}
10931 	    	quantity+="</select></span>";
10932     	}
10933     	else{
10934     		quantity = "";
10935     	}
10936     	var options = "";
10937     	var productsSelect = "<select id=\""+instanceId+"_products\" style=\"display: "+((data.hideSingle!=undefined&&data.hideSingle&&products.length==1)?"none":"")+"\">";
10938     	for(var index in products){
10939     		var product = products[index];
10940     		 productsSelect+="<option value=\""+product.id+"\">"+product.text+"</option>";
10941     		 if(product.options!=undefined){
10942     		 	options+="<select id=\""+instanceId+"_"+product.id+"\" class=\""+instanceId+"_options\">";
10943     		 	for(var index in product.options){
10944     		 		var option = product.options[index];
10945     		 		var text = option[1];
10946     		 		var optionValue = option[0];
10947     		 		options+="<option value=\""+optionValue+"\">"+text+"</option>";
10948     		 	}
10949     		 	options+="</select>";
10950     		 }
10951     	}
10952     	if(options.length>0){
10953     		options = "<br />"+options;
10954     	}
10955     	productsSelect+="</select>";
10956         var html = ""+
10957 "<form id=\""+instanceId+"_form\" action=\""+paypalUrl+"\" method=\"post\" style=\"display: none;\">"+
10958 "<input type=\"hidden\" name=\"cmd\" value=\"_s-xclick\">"+ 
10959 //"<input type=\"hidden\" name=\"custom\" value=\""+SETTINGS['user']['id']+"\">"+  
10960 "<input type=\"hidden\" id=\""+instanceId+"_quantityField\" name=\"quantity\" value=\"\">"+
10961 "<input type=\"hidden\" id=\""+instanceId+"_productId\" name=\"hosted_button_id\" value=\"\">"+
10962 "<input type=\"image\" src=\"https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif\" border=\"0\" name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\">"+
10963 "<img alt=\"\" border=\"0\" src=\"https://www.paypalobjects.com/en_US/i/scr/pixel.gif\" width=\"1\" height=\"1\">"+
10964 "</form>"+productsSelect+options+quantity+"<br /><br /><span id=\""+instanceId+"_button\" style=\"margin: 0 auto; "+(showButton?"":"display:none;")+"\" class=\"button\">"+buttonText+"</span>";   
10965         return html;
10966     }
10967     this.destroy=function(){
10968     }                                                    
10969 }
10970 WIDGETS.register("PayPalOptionButton", PayPalOptionButton); 
10971 
10972 function PayPalBuyNowWidget(instanceId, data){
10973 	var paypalUrl = (data.sandboxMode!=undefined&&(data.sandboxMode==true||data.sandboxMode=="true"))?"https://www.sandbox.paypal.com/cgi-bin/webscr":"https://www.paypal.com/cgi-bin/webscr";
10974 	var productId = data.productId;
10975     var options = (data.optionName==undefined)?"":"<input type=\"hidden\"name=\"on0\" value=\""+data.optionName+"\"><input type=\"hidden\" id=\""+instanceId+"_option\" name=\"os0\" value=\""+data.optionValue+"\" />";
10976     var buttonText = data.text==undefined||data.text.length===0?"Purchase Now":data.text; 
10977     var autoSubmit = (data.autoSubmit!=undefined)?data.autoSubmit:true;
10978     var showButton = (data.showButton!=undefined)?data.showButton:true;
10979     this.invoiceE = undefined;
10980     var requestInvoiceE = F.receiverE();
10981     this.loader=function(){
10982     	var buttonClickedE = F.extractEventE(instanceId+"_button", "click").mapE(function(){return {};});  
10983         this.invoiceE = getAjaxRequestE(F.mergeE(requestInvoiceE, buttonClickedE.mapE(function(){return true;})), "/request/products_createInvoice").mapE(function(invoice){
10984         	DOM.get(instanceId+"_form").innerHTML+="<input type='hidden' name='invoice' value='"+invoice.invoiceId+"' />";
10985         	if(autoSubmit){
10986         		DOM.get(instanceId+"_form").submit();
10987         	}
10988         	return invoice;
10989         });  
10990     }
10991     this.setOptionValue = function(value){
10992     	DOM.get(instanceId+"_option").value = value;
10993     };
10994     this.requestInvoice = function(option){
10995     	requestInvoiceE.sendEvent((option==undefined?true:option));
10996     };
10997     this.getForm = function(){
10998     	return DOM.get(instanceId+"_form");
10999     };
11000     this.submit = function(){
11001     	DOM.get(instanceId+"_form").submit();
11002     	/*this.requestInvoice();
11003     	autoSubmit = true;*/
11004     }
11005     this.build=function(){
11006         var html = ""+
11007 "<form id=\""+instanceId+"_form\" action=\""+paypalUrl+"\" method=\"post\" style=\"display: none;\">"+
11008 "<input type=\"hidden\" name=\"cmd\" value=\"_s-xclick\">"+ 
11009 //"<input type=\"hidden\" name=\"custom\" value=\""+SETTINGS['user']['id']+"\">"+  
11010 "<input type=\"hidden\" name=\"hosted_button_id\" value=\""+productId+"\">"+options+
11011 "<input type=\"image\" src=\"https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif\" border=\"0\" name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\">"+
11012 "<img alt=\"\" border=\"0\" src=\"https://www.paypalobjects.com/en_US/i/scr/pixel.gif\" width=\"1\" height=\"1\">"+
11013 "</form><br /><span id=\""+instanceId+"_button\" style=\"margin: 0 auto; "+(showButton?"":"display:none;")+"\" class=\"button\">"+buttonText+"</span>";   
11014         return html;
11015     }
11016     this.destroy=function(){
11017     }                                                    
11018 }
11019 
11020 
11021 
11022 
11023 
11024 /**
11025  *  ProductSelectionWidgetConfigurator
11026  * @constructor
11027  */                                                      
11028 function PayPalBuyNowWidgetConfigurator(){
11029     var id = "PayPalBuyNowWidgetConfigurator";
11030     this['load'] = function(newData){}
11031     this['build'] = function(newData){
11032         var productId = "";
11033         var optionName = ""; 
11034         var text = "";    
11035         if(newData!=undefined){
11036             productId = newData['productId'];
11037             optionName = newData['optionName']; 
11038             text = newData['text'];   
11039         }
11040         return "Product Id: <input type=\"text\" id=\""+id+"_productId\" value=\""+productId+"\" /><br />"+
11041         "Option Name: <input type=\"text\" id=\""+id+"_optionName\" value=\""+optionName+"\" />"+
11042         "Text: <input type=\"text\" value=\""+text+"\" id=\""+id+"_text\" />";    
11043               
11044         //   productId      optionName
11045     }
11046     this['getData'] = function(){
11047         return {"productId": document.getElementById(id+'_productId').value, "optionName": document.getElementById(id+'_optionName').value, "text": document.getElementById(id+'_text').value};
11048     }
11049     this['getName'] = function(){
11050         return "PayPay Buy Now Button";
11051     }
11052     this['getDescription'] = function(){
11053         return "A Pay Pal Widget With HTML Option Selector";
11054     }
11055     this['getPackage'] = function(){
11056         return "Products";
11057     }
11058 } 
11059 WIDGETS.register("PayPalBuyNowWidget", PayPalBuyNowWidget, PayPalBuyNowWidgetConfigurator); 
11060 
11061 
11062 
11063 
11064 
11065 function PayPalOrderStatusChecker(instanceId, data){
11066     this.loader = function(){
11067 	    if(getVars.tx!=undefined){
11068 	    	var transactionId = getVars.tx;
11069 	    	var serverResponseE = getAjaxRequestE(F.oneE().mapE(function(){return {tx: transactionId}}), "/request/paypal_paymentreturn").mapE(function(response){
11070 		    	log("Server Response");
11071 		    	log(response);
11072 		    });
11073     	}
11074     }
11075     this.build=function(){}
11076     this.destroy=function(){
11077     }                                                    
11078 }
11079 WIDGETS.register("PayPalOrderStatusChecker", PayPalOrderStatusChecker); 
11080 window['CKEDITOR_BASEPATH'] = window['SETTINGS']['scriptPath']+'plugins/ckeditor/ckeditor/';
11081 pageDataB.calmB().liftB(function(pageData){
11082     if(pageData==NOT_READY){
11083         return NOT_READY;
11084     }
11085  //getElementById("content")
11086  var element = document.createElement("span");
11087 if(window['SETTINGS']['page']['permissions']['canEdit'] || window['SETTINGS']['page']['permissions']['canDelete']){
11088     var adminPanel = document.createElement("span");
11089     adminPanel.id = "aurora_adminPanel";
11090     adminPanel.style.position = 'absolute';
11091     adminPanel.style.top = '0px';
11092     adminPanel.style.right = '0px';
11093     
11094     //adminPanel.style = "position: absolute; top: 0px; right: 0px;";
11095     if(window['SETTINGS']['page']['permissions']['canEdit']){
11096         adminPanel.innerHTML += "<a href=\"javascript:editPage();\"><img style=\"width: 20px; height: 20px;\" src=\""+window['SETTINGS']['scriptPath']+"plugins/ckeditor/edit.png\" alt=\"\" /></a>";   
11097     }
11098     if(window['SETTINGS']['page']['permissions']['canDelete']){
11099         adminPanel.innerHTML += "<a href=\"javascript:deletePage();\"><img style=\"width: 20px; height: 20px;\" src=\""+window['SETTINGS']['scriptPath']+"plugins/ckeditor/delete.png\" alt=\"\" /></a>";   
11100     }
11101     document['body'].appendChild(adminPanel);                                                  
11102 }
11103  
11104  });                                                                         
11105            
11106      
11107 function findLinks(parent,callback){
11108     child = parent.firstChild;
11109     while(child){
11110         if(child.nodeName.toLowerCase()=="a"){
11111             callback(child);
11112         }
11113         if(child.hasChildNodes()){               
11114             //parent.replaceChild(replaceLinkPaths(child, search, replace), child);
11115             child = findLinks(child,callback);
11116         }
11117         if(child.nextSibling==null)  //Needed for weird old browser compatibility
11118             return parent;// parent;
11119         child = child.nextSibling;
11120     }
11121     return parent;
11122 }   
11123 function cleanUpHtml(html){
11124     var element = document.createElement("div");
11125     element.innerHTML = html;
11126     findLinks(element, function(child){
11127         var pageName = child.href.replaceAll(window['SETTINGS']['scriptPath'], "");
11128         child.href = child.href.replaceAll(window['SETTINGS']['scriptPath'], "page://");
11129         log('Hurr2');  
11130         child.onclick = function(){loadPage(pageName)};
11131     });
11132     return element.innerHTML;
11133 }
11134             
11135             
11136 function cleanDownHtml(html){
11137     var element = document.createElement("div");
11138     element.innerHTML = html;
11139     element = findLinks(element, function(child){
11140     var pageName = child.href.replaceAll("page://", "");
11141         child.href = child.href.replaceAll("page://", window['SETTINGS']['scriptPath']);
11142         log('Hurr');
11143         child.onclick = function(){loadPage(pageName);return false;};
11144     });
11145     return element.innerHTML;
11146 }
11147               
11148  function showBodyEditor(theme, page){
11149     editorOpen = true; 
11150     
11151     theme = cleanUpHtml(theme);
11152     page = cleanUpHtml(page);
11153                                     
11154     document.getElementById("body").innerHTML = theme;
11155     document.getElementById("content").innerHTML = page;
11156     
11157     var editor = CKEDITOR.replace('body', {'customConfig': window['SETTINGS']['scriptPath']+'themes/'+window['SETTINGS']['theme']['name']+'/auroraPageBodyConfig.js', 'extraPlugins' : 'ajaxSave,auroraWidgets,auroraCancel' });               
11158     CKEDITOR.on('instanceReady',function() {editor.execCommand('maximize');});
11159     }
11160 function showContentEditor(data){
11161     editorOpen = true;
11162     data = cleanUpHtml(data); 
11163     
11164     var outerContent = document.createElement("div");
11165     var content =  document.getElementById("content");
11166     content.parentNode.replaceChild(outerContent,content); 
11167     outerContent.appendChild(content);
11168     
11169     document.getElementById("content").innerHTML = data;
11170     //function() {jQuery.scrollTo(outerContent, 1000);jQuery("#aurora_adminPanel").hide();}
11171     CKEDITOR.replace('content', {'customConfig': window['SETTINGS']['scriptPath']+'themes/'+window['SETTINGS']['theme']['name']+'/auroraPageConfig.js', 'extraPlugins' : 'ajaxSave,auroraWidgets,auroraCancel' });               
11172     CKEDITOR.on('instanceReady',function() {
11173         if(typeof jQuery!='undefined'){
11174             jQuery.scrollTo(outerContent, 1000);
11175             jQuery("#aurora_adminPanel").hide();
11176         }
11177         else{
11178             var pos = getPos(outerContent);
11179             window.scrollTo(0, pos.y);
11180             document.getElementById('aurora_adminPanel').style.display = 'none';
11181         }
11182     });
11183 } 
11184 window['ckeditor_ajaxSave'] = function(editor){
11185     var data = cleanDownHtml(editor.getData());
11186     if(isBase()){
11187         var sendData;
11188         sendData = seperateContentFromTheme(data);
11189         if(sendData.content.length==0)
11190             alert("Error - Your template MUST contain a div with an id of 'content'");
11191         else{
11192             commitPageChanges(sendData, editor);
11193         }
11194     }
11195     else{
11196         var groupsHTML = "";
11197         for(index in window['SETTINGS']['groups']){
11198             var group = window['SETTINGS']['groups'][index];
11199             var checked = checkPermission(group['group_id'])?" checked=\"yes\"":"";
11200             groupsHTML+="<input type=\"checkbox\" name=\""+group['group_id']+"\" id=\"groupcheck_"+group['group_id']+"\" "+checked+" /> "+group['name']+"<br />";    
11201         }                                  
11202         UI.showMessage("Who can view this page?", groupsHTML, function(){
11203             var groupsAllowed = new Object();
11204             for(index in window['SETTINGS']['groups']){
11205                 groupsAllowed[window['SETTINGS']['groups'][index]['group_id']] = document.getElementById("groupcheck_"+window['SETTINGS']['groups'][index]['group_id']).checked;
11206             }
11207             sendData = {"content": data, "pageName": window['SETTINGS']['page']['name']+"", "permissions": groupsAllowed};
11208             commitPageChanges(sendData, editor);
11209         }); 
11210     }
11211     editorOpen = false;
11212 };
11213 function seperateContentFromTheme(data){
11214     var element = document.createElement('div');
11215     element.innerHTML = data;    
11216     divs = element.getElementsByTagName('div');
11217     var contentHTML = "";
11218     for (i=0;i<divs.length;i++){
11219         var div = divs[i];//.childNodes[0].nodeValue; 
11220         if(div.id=="content"){
11221             contentHTML = div.innerHTML; 
11222             div.innerHTML = "<PAGE_CONTENT>";
11223         }
11224         else if(div.id=="aurora_adminPanel"){
11225             div.parentNode.removeChild(div);
11226         }
11227     } 
11228     return {"content": contentHTML, "template": element.innerHTML, "pageName": window['SETTINGS']['page']['name']+""};
11229 } 
11230 function removeAdminPanel(data){
11231     var element = document.createElement('div');
11232     element.innerHTML = data;    
11233     divs = element.getElementsByTagName('div');
11234     var contentHTML = "";
11235     for (i=0;i<divs.length;i++){
11236         var div = divs[i];
11237         if(div.id=="aurora_adminPanel")
11238             div.parentNode.removeChild(div);
11239     } 
11240     return element.innerHTML;
11241 }                                      
11242 window['afterCommit'] = function(data, editor){
11243     (editor['destroy'])();
11244     window.location=window['SETTINGS']['scriptPath']+window['SETTINGS']['page']['name'];
11245 };
11246 window['cancelPageEdit'] = function(){
11247     window.location=window['SETTINGS']['scriptPath']+window['SETTINGS']['page']['name'];
11248 };
11249 
11250 window['editPage'] = function(){
11251     if(isBase())
11252         showBodyEditor(window['SETTINGS']['theme']['html'], window['SETTINGS']['page']['html']);
11253     else
11254         showContentEditor(window['SETTINGS']['page']['html']);
11255 };
11256 window['deletePage'] = function(){
11257     UI.confirm("Delete Page", "Are you sure you wish to delete this page?", "Yes", function(val){
11258             ajax({"type": "post",
11259                 "url": window['SETTINGS']['scriptPath'] +"request/deletePage",
11260                 "data": {"pageName": window['SETTINGS']['page']['name']+""},
11261                 "success": function(data){window['location']=window['SETTINGS']['scriptPath']+window['SETTINGS']['defaultPage'];}
11262                 });  
11263         }, "No",
11264         function(val){
11265             
11266         });
11267 };   
11268 window['commitPageChanges'] = function(dataObj, editor){
11269     ajax({"type": "post",
11270         "url": window['SETTINGS']['scriptPath'] +"request/commitPage",
11271         "data": dataObj,
11272         "success": function(data){afterCommit(data, editor);}
11273         });
11274 };
11275 function ContactFormSubmitButton(instanceId, data){
11276     this.instanceId = instanceId;
11277     var loadingImId = this.instanceId+"_loading";
11278     var submitButton = new ValidatedSubmitButton(instanceId,data);
11279     this.loader=function(){           
11280         
11281         var formDataGroupB = DATA.get(data.formGroup, undefined, {}); 
11282         var formDataB = formDataGroupB.liftB(function(validationMap){
11283             return F.liftB.apply(this,[function(){
11284                 var dataOb = {};
11285                 for(index in arguments){         
11286                     if(arguments[index].valid){
11287                         dataOb[arguments[index].name] = arguments[index].value;                            
11288                     }
11289                 }
11290                 return dataOb;
11291             }].concat(getObjectValues(validationMap)));
11292         }).switchB();
11293         
11294         submitButton.loader();    
11295         var submitClickedE = jQuery("#"+submitButton.elementId).fj('extEvtE', 'click').snapshotE(formDataB).mapE(function(formData){
11296             if(data.subject!=undefined){
11297                 	formData.subject = data.subject;
11298                 }
11299             return formData;
11300         });
11301         var submitClickedB = submitClickedE.startsWith(NOT_READY);
11302          
11303         /*var submitClickedE = jQuery("#"+submitButton.elementId).fj('extEvtE', 'click').snapshotE(formDataB).mapE(function(formDataMap){
11304             alert("Submit clicked");
11305             return formDataB;
11306         });   */            
11307         getAjaxRequestB(submitClickedB, SETTINGS['scriptPath']+"request/contactForm_sendMessage/").mapE(function(valid){
11308             UI.showMessage('Contact Form', (data.text!=undefined?data.text:'Your request has been sent.'));
11309             return valid;    
11310         });  
11311         //groupValidB
11312         
11313         //var emailValidB = F.receiverE().startsWith(false);
11314         //F.insertValueB(emailValidB,loadingImId, 'src');
11315         //F.insertValueB(submitClickedE.mapE(function(){return SETTINGS['theme']['path']+'loading_s.gif';}),loadingImId, 'src');
11316     }
11317     this.build=function(){
11318         return ""+submitButton.build()+"<img id=\""+loadingImId+"\" class=\"loadingSpinner\" src=\"/resources/trans.png\" alt=\"\" />";                 
11319     }
11320 }
11321 WIDGETS.register("ContactFormSubmitButton", ContactFormSubmitButton);
11322 /*! jQuery Dynatree Plugin - v1.2.4 - 2013-02-12
11323 * http://dynatree.googlecode.com/
11324 * Copyright (c) 2013 Martin Wendt; Licensed MIT, GPL */
11325 function _log(e,t){if(!_canLog)return;var n=Array.prototype.slice.apply(arguments,[1]),r=new Date,i=r.getHours()+":"+r.getMinutes()+":"+r.getSeconds()+"."+r.getMilliseconds();n[0]=i+" - "+n[0];try{switch(e){case"info":window.console.info.apply(window.console,n);break;case"warn":window.console.warn.apply(window.console,n);break;default:window.console.log.apply(window.console,n)}}catch(s){window.console?s.number===-2146827850&&window.console.log(n.join(", ")):_canLog=!1}}function _checkBrowser(){function n(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}}var e,t;return e=n(navigator.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),t}function logMsg(e){Array.prototype.unshift.apply(arguments,["debug"]),_log.apply(this,arguments)}var _canLog=!0,BROWSER=jQuery.browser||_checkBrowser(),getDynaTreePersistData=null,DTNodeStatus_Error=-1,DTNodeStatus_Loading=1,DTNodeStatus_Ok=0;(function($){function getDtNodeFromElement(e){return alert("getDtNodeFromElement is deprecated"),$.ui.dynatree.getNode(e)}function noop(){}function versionCompare(e,t){var n=(""+e).split("."),r=(""+t).split("."),i=Math.min(n.length,r.length),s,o,u;for(u=0;u<i;u++){s=parseInt(n[u],10),o=parseInt(r[u],10),isNaN(s)&&(s=n[u]),isNaN(o)&&(o=r[u]);if(s==o)continue;return s>o?1:s<o?-1:NaN}return n.length===r.length?0:n.length<r.length?-1:1}function _initDragAndDrop(e){var t=e.options.dnd||null;t&&(t.onDragStart||t.onDrop)&&_registerDnd(),t&&t.onDragStart&&e.$tree.draggable({addClasses:!1,appendTo:"body",containment:!1,delay:0,distance:4,revert:!1,scroll:!0,scrollSpeed:7,scrollSensitivity:10,connectToDynatree:!0,helper:function(e){var t=$.ui.dynatree.getNode(e.target);return t?t.tree._onDragEvent("helper",t,null,e,null,null):"<div></div>"},start:function(e,t){var n=t.helper.data("dtSourceNode");return!!n},_last:null}),t&&t.onDrop&&e.$tree.droppable({addClasses:!1,tolerance:"intersect",greedy:!1,_last:null})}var Class={create:function(){return function(){this.initialize.apply(this,arguments)}}},DynaTreeNode=Class.create();DynaTreeNode.prototype={initialize:function(e,t,n){this.parent=e,this.tree=t,typeof n=="string"&&(n={title:n}),n.key?n.key=""+n.key:n.key="_"+t._nodeCount++,this.data=$.extend({},$.ui.dynatree.nodedatadefaults,n),this.li=null,this.span=null,this.ul=null,this.childList=null,this._isLoading=!1,this.hasSubSel=!1,this.bExpanded=!1,this.bSelected=!1},toString:function(){return"DynaTreeNode<"+this.data.key+">: '"+this.data.title+"'"},toDict:function(e,t){var n=$.extend({},this.data);n.activate=this.tree.activeNode===this,n.focus=this.tree.focusNode===this,n.expand=this.bExpanded,n.select=this.bSelected,t&&t(n);if(e&&this.childList){n.children=[];for(var r=0,i=this.childList.length;r<i;r++)n.children.push(this.childList[r].toDict(!0,t))}else delete n.children;return n},fromDict:function(e){var t=e.children;if(t===undefined){this.data=$.extend(this.data,e),this.render();return}e=$.extend({},e),e.children=undefined,this.data=$.extend(this.data,e),this.removeChildren(),this.addChild(t)},_getInnerHtml:function(){var e=this.tree,t=e.options,n=e.cache,r=this.getLevel(),i=this.data,s="",o;r<t.minExpandLevel?r>1&&(s+=n.tagConnector):this.hasChildren()!==!1?s+=n.tagExpander:s+=n.tagConnector,t.checkbox&&i.hideCheckbox!==!0&&!i.isStatusNode&&(s+=n.tagCheckbox),i.icon?(i.icon.charAt(0)==="/"?o=i.icon:o=t.imagePath+i.icon,s+="<img src='"+o+"' alt='' />"):i.icon!==!1&&(i.iconClass?s+="<span class=' "+i.iconClass+"'></span>":s+=n.tagNodeIcon);var u="";t.onCustomRender&&(u=t.onCustomRender.call(e,this)||"");if(!u){var a=i.tooltip?' title="'+i.tooltip.replace(/\"/g,""")+'"':"",f=i.href||"#";t.noLink||i.noLink?u='<span style="display:inline-block;" class="'+t.classNames.title+'"'+a+">"+i.title+"</span>":u='<a href="'+f+'" class="'+t.classNames.title+'"'+a+">"+i.title+"</a>"}return s+=u,s},_fixOrder:function(){var e=this.childList;if(!e||!this.ul)return;var t=this.ul.firstChild;for(var n=0,r=e.length-1;n<r;n++){var i=e[n],s=t.dtnode;i!==s?(this.tree.logDebug("_fixOrder: mismatch at index "+n+": "+i+" != "+s),this.ul.insertBefore(i.li,s.li)):t=t.nextSibling}},render:function(e,t){var n=this.tree,r=this.parent,i=this.data,s=n.options,o=s.classNames,u=this.isLastSibling(),a=!1;if(!r&&!this.ul)this.li=this.span=null,this.ul=document.createElement("ul"),s.minExpandLevel>1?this.ul.className=o.container+" "+o.noConnector:this.ul.className=o.container;else if(r){this.li||(a=!0,this.li=document.createElement("li"),this.li.dtnode=this,i.key&&s.generateIds&&(this.li.id=s.idPrefix+i.key),this.span=document.createElement("span"),this.span.className=o.title,this.li.appendChild(this.span),r.ul||(r.ul=document.createElement("ul"),r.ul.style.display="none",r.li.appendChild(r.ul)),r.ul.appendChild(this.li)),this.span.innerHTML=this._getInnerHtml();var f=[];f.push(o.node),i.isFolder&&f.push(o.folder),this.bExpanded&&f.push(o.expanded),this.hasChildren()!==!1&&f.push(o.hasChildren),i.isLazy&&this.childList===null&&f.push(o.lazy),u&&f.push(o.lastsib),this.bSelected&&f.push(o.selected),this.hasSubSel&&f.push(o.partsel),n.activeNode===this&&f.push(o.active),i.addClass&&f.push(i.addClass),f.push(o.combinedExpanderPrefix+(this.bExpanded?"e":"c")+(i.isLazy&&this.childList===null?"d":"")+(u?"l":"")),f.push(o.combinedIconPrefix+(this.bExpanded?"e":"c")+(i.isFolder?"f":"")),this.span.className=f.join(" "),this.li.className=u?o.lastsib:"",a&&s.onCreate&&s.onCreate.call(n,this,this.span),s.onRender&&s.onRender.call(n,this,this.span)}if((this.bExpanded||t===!0)&&this.childList){for(var l=0,c=this.childList.length;l<c;l++)this.childList[l].render(!1,t);this._fixOrder()}if(this.ul){var h=this.ul.style.display==="none",p=!!this.bExpanded;if(e&&s.fx&&h===p){var d=s.fx.duration||200;$(this.ul).animate(s.fx,d)}else this.ul.style.display=this.bExpanded||!r?"":"none"}},getKeyPath:function(e){var t=[];return this.visitParents(function(e){e.parent&&t.unshift(e.data.key)},!e),"/"+t.join(this.tree.options.keyPathSeparator)},getParent:function(){return this.parent},getChildren:function(){return this.hasChildren()===undefined?undefined:this.childList},hasChildren:function(){if(this.data.isLazy)return this.childList===null||this.childList===undefined?undefined:this.childList.length===0?!1:this.childList.length===1&&this.childList[0].isStatusNode()?undefined:!0;return!!this.childList},isFirstSibling:function(){var e=this.parent;return!e||e.childList[0]===this},isLastSibling:function(){var e=this.parent;return!e||e.childList[e.childList.length-1]===this},isLoading:function(){return!!this._isLoading},getPrevSibling:function(){if(!this.parent)return null;var e=this.parent.childList;for(var t=1,n=e.length;t<n;t++)if(e[t]===this)return e[t-1];return null},getNextSibling:function(){if(!this.parent)return null;var e=this.parent.childList;for(var t=0,n=e.length-1;t<n;t++)if(e[t]===this)return e[t+1];return null},isStatusNode:function(){return this.data.isStatusNode===!0},isChildOf:function(e){return this.parent&&this.parent===e},isDescendantOf:function(e){if(!e)return!1;var t=this.parent;while(t){if(t===e)return!0;t=t.parent}return!1},countChildren:function(){var e=this.childList;if(!e)return 0;var t=e.length;for(var n=0,r=t;n<r;n++){var i=e[n];t+=i.countChildren()}return t},sortChildren:function(e,t){var n=this.childList;if(!n)return;e=e||function(e,t){var n=e.data.title.toLowerCase(),r=t.data.title.toLowerCase();return n===r?0:n>r?1:-1},n.sort(e);if(t)for(var r=0,i=n.length;r<i;r++)n[r].childList&&n[r].sortChildren(e,"$norender$");t!=="$norender$"&&this.render()},_setStatusNode:function(e){var t=this.childList?this.childList[0]:null;if(!e){if(t&&t.isStatusNode()){try{this.ul&&(this.ul.removeChild(t.li),t.li=null)}catch(n){}this.childList.length===1?this.childList=[]:this.childList.shift()}}else t?(e.isStatusNode=!0,e.key="_statusNode",t.data=e,t.render()):(e.isStatusNode=!0,e.key="_statusNode",t=this.addChild(e))},setLazyNodeStatus:function(e,t){var n=t&&t.tooltip?t.tooltip:null,r=t&&t.info?" ("+t.info+")":"";switch(e){case DTNodeStatus_Ok:this._setStatusNode(null),$(this.span).removeClass(this.tree.options.classNames.nodeLoading),this._isLoading=!1,this.tree.options.autoFocus&&(this===this.tree.tnRoot&&this.childList&&this.childList.length>0?this.childList[0].focus():this.focus());break;case DTNodeStatus_Loading:this._isLoading=!0,$(this.span).addClass(this.tree.options.classNames.nodeLoading),this.parent||this._setStatusNode({title:this.tree.options.strings.loading+r,tooltip:n,addClass:this.tree.options.classNames.nodeWait});break;case DTNodeStatus_Error:this._isLoading=!1,this._setStatusNode({title:this.tree.options.strings.loadError+r,tooltip:n,addClass:this.tree.options.classNames.nodeError});break;default:throw"Bad LazyNodeStatus: '"+e+"'."}},_parentList:function(e,t){var n=[],r=t?this:this.parent;while(r)(e||r.parent)&&n.unshift(r),r=r.parent;return n},getLevel:function(){var e=0,t=this.parent;while(t)e++,t=t.parent;return e},_getTypeForOuterNodeEvent:function(e){var t=this.tree.options.classNames,n=e.target;if(n.className.indexOf(t.node)<0)return null;var r=e.pageX-n.offsetLeft,i=e.pageY-n.offsetTop;for(var s=0,o=n.childNodes.length;s<o;s++){var u=n.childNodes[s],a=u.offsetLeft-n.offsetLeft,f=u.offsetTop-n.offsetTop,l=u.clientWidth,c=u.clientHeight;if(r>=a&&r<=a+l&&i>=f&&i<=f+c){if(u.className==t.title)return"title";if(u.className==t.expander)return"expander";if(u.className==t.checkbox)return"checkbox";if(u.className==t.nodeIcon)return"icon"}}return"prefix"},getEventTargetType:function(e){var t=e&&e.target?e.target.className:"",n=this.tree.options.classNames;return t===n.title?"title":t===n.expander?"expander":t===n.checkbox?"checkbox":t===n.nodeIcon?"icon":t===n.empty||t===n.vline||t===n.connector?"prefix":t.indexOf(n.node)>=0?this._getTypeForOuterNodeEvent(e):null},isVisible:function(){var e=this._parentList(!0,!1);for(var t=0,n=e.length;t<n;t++)if(!e[t].bExpanded)return!1;return!0},makeVisible:function(){var e=this._parentList(!0,!1);for(var t=0,n=e.length;t<n;t++)e[t]._expand(!0)},focus:function(){this.makeVisible();try{$(this.span).find(">a").focus()}catch(e){}},isFocused:function(){return this.tree.tnFocused===this},_activate:function(e,t){this.tree.logDebug("dtnode._activate(%o, fireEvents=%o) - %o",e,t,this);var n=this.tree.options;if(this.data.isStatusNode)return;if(t&&n.onQueryActivate&&n.onQueryActivate.call(this.tree,e,this)===!1)return;if(e){if(this.tree.activeNode){if(this.tree.activeNode===this)return;this.tree.activeNode.deactivate()}n.activeVisible&&this.makeVisible(),this.tree.activeNode=this,n.persist&&$.cookie(n.cookieId+"-active",this.data.key,n.cookie),this.tree.persistence.activeKey=this.data.key,$(this.span).addClass(n.classNames.active),t&&n.onActivate&&n.onActivate.call(this.tree,this)}else if(this.tree.activeNode===this){if(n.onQueryActivate&&n.onQueryActivate.call(this.tree,!1,this)===!1)return;$(this.span).removeClass(n.classNames.active),n.persist&&$.cookie(n.cookieId+"-active","",n.cookie),this.tree.persistence.activeKey=null,this.tree.activeNode=null,t&&n.onDeactivate&&n.onDeactivate.call(this.tree,this)}},activate:function(){this._activate(!0,!0)},activateSilently:function(){this._activate(!0,!1)},deactivate:function(){this._activate(!1,!0)},isActive:function(){return this.tree.activeNode===this},_userActivate:function(){var e=!0,t=!1;if(this.data.isFolder)switch(this.tree.options.clickFolderMode){case 2:e=!1,t=!0;break;case 3:e=t=!0}this.parent===null&&(t=!1),t&&(this.toggleExpand(),this.focus()),e&&this.activate()},_setSubSel:function(e){e?(this.hasSubSel=!0,$(this.span).addClass(this.tree.options.classNames.partsel)):(this.hasSubSel=!1,$(this.span).removeClass(this.tree.options.classNames.partsel))},_updatePartSelectionState:function(){var e;if(!this.hasChildren())return e=this.bSelected&&!this.data.unselectable&&!this.data.isStatusNode,this._setSubSel(!1),e;var t,n,r=this.childList,i=!0,s=!0;for(t=0,n=r.length;t<n;t++){var o=r[t],u=o._updatePartSelectionState();u!==!1&&(s=!1),u!==!0&&(i=!1)}return i?e=!0:s?e=!1:e=undefined,this._setSubSel(e===undefined),this.bSelected=e===!0,e},_fixSelectionState:function(){var e,t,n;if(this.bSelected){this.visit(function(e){e.parent._setSubSel(!0),e.data.unselectable||e._select(!0,!1,!1)}),e=this.parent;while(e){e._setSubSel(!0);var r=!0;for(t=0,n=e.childList.length;t<n;t++){var i=e.childList[t];if(!i.bSelected&&!i.data.isStatusNode&&!i.data.unselectable){r=!1;break}}r&&e._select(!0,!1,!1),e=e.parent}}else{this._setSubSel(!1),this.visit(function(e){e._setSubSel(!1),e._select(!1,!1,!1)}),e=this.parent;while(e){e._select(!1,!1,!1);var s=!1;for(t=0,n=e.childList.length;t<n;t++)if(e.childList[t].bSelected||e.childList[t].hasSubSel){s=!0;break}e._setSubSel(s),e=e.parent}}},_select:function(e,t,n){var r=this.tree.options;if(this.data.isStatusNode)return;if(this.bSelected===e)return;if(t&&r.onQuerySelect&&r.onQuerySelect.call(this.tree,e,this)===!1)return;r.selectMode==1&&e&&this.tree.visit(function(e){if(e.bSelected)return e._select(!1,!1,!1),!1}),this.bSelected=e,e?(r.persist&&this.tree.persistence.addSelect(this.data.key),$(this.span).addClass(r.classNames.selected),n&&r.selectMode===3&&this._fixSelectionState(),t&&r.onSelect&&r.onSelect.call(this.tree,!0,this)):(r.persist&&this.tree.persistence.clearSelect(this.data.key),$(this.span).removeClass(r.classNames.selected),n&&r.selectMode===3&&this._fixSelectionState(),t&&r.onSelect&&r.onSelect.call(this.tree,!1,this))},select:function(e){return this.data.unselectable?this.bSelected:this._select(e!==!1,!0,!0)},toggleSelect:function(){return this.select(!this.bSelected)},isSelected:function(){return this.bSelected},isLazy:function(){return!!this.data.isLazy},_loadContent:function(){try{var e=this.tree.options;this.tree.logDebug("_loadContent: start - %o",this),this.setLazyNodeStatus(DTNodeStatus_Loading),!0===e.onLazyRead.call(this.tree,this)&&(this.setLazyNodeStatus(DTNodeStatus_Ok),this.tree.logDebug("_loadContent: succeeded - %o",this))}catch(t){this.tree.logWarning("_loadContent: failed - %o",t),this.setLazyNodeStatus(DTNodeStatus_Error,{tooltip:""+t})}},_expand:function(e,t){if(this.bExpanded===e){this.tree.logDebug("dtnode._expand(%o) IGNORED - %o",e,this);return}this.tree.logDebug("dtnode._expand(%o) - %o",e,this);var n=this.tree.options;if(!e&&this.getLevel()<n.minExpandLevel){this.tree.logDebug("dtnode._expand(%o) prevented collapse - %o",e,this);return}if(n.onQueryExpand&&n.onQueryExpand.call(this.tree,e,this)===!1)return;this.bExpanded=e,n.persist&&(e?this.tree.persistence.addExpand(this.data.key):this.tree.persistence.clearExpand(this.data.key));var r=(!this.data.isLazy||this.childList!==null)&&!this._isLoading&&!t;this.render(r);if(this.bExpanded&&this.parent&&n.autoCollapse){var i=this._parentList(!1,!0);for(var s=0,o=i.length;s<o;s++)i[s].collapseSiblings()}n.activeVisible&&this.tree.activeNode&&!this.tree.activeNode.isVisible()&&this.tree.activeNode.deactivate();if(e&&this.data.isLazy&&this.childList===null&&!this._isLoading){this._loadContent();return}n.onExpand&&n.onExpand.call(this.tree,e,this)},isExpanded:function(){return this.bExpanded},expand:function(e){e=e!==!1;if(!this.childList&&!this.data.isLazy&&e)return;if(this.parent===null&&!e)return;this._expand(e)},scheduleAction:function(e,t){this.tree.timer&&(clearTimeout(this.tree.timer),this.tree.logDebug("clearTimeout(%o)",this.tree.timer));var n=this;switch(e){case"cancel":break;case"expand":this.tree.timer=setTimeout(function(){n.tree.logDebug("setTimeout: trigger expand"),n.expand(!0)},t);break;case"activate":this.tree.timer=setTimeout(function(){n.tree.logDebug("setTimeout: trigger activate"),n.activate()},t);break;default:throw"Invalid mode "+e}this.tree.logDebug("setTimeout(%s, %s): %s",e,t,this.tree.timer)},toggleExpand:function(){this.expand(!this.bExpanded)},collapseSiblings:function(){if(this.parent===null)return;var e=this.parent.childList;for(var t=0,n=e.length;t<n;t++)e[t]!==this&&e[t].bExpanded&&e[t]._expand(!1)},_onClick:function(e){var t=this.getEventTargetType(e);if(t==="expander")this.toggleExpand(),this.focus();else if(t==="checkbox")this.toggleSelect(),this.focus();else{this._userActivate();var n=this.span.getElementsByTagName("a");if(!n[0])return!0;BROWSER.msie&&parseInt(BROWSER.version,10)<9||n[0].focus()}e.preventDefault()},_onDblClick:function(e){},_onKeydown:function(e){var t=!0,n;switch(e.which){case 107:case 187:this.bExpanded||this.toggleExpand();break;case 109:case 189:this.bExpanded&&this.toggleExpand();break;case 32:this._userActivate();break;case 8:this.parent&&this.parent.focus();break;case 37:this.bExpanded?(this.toggleExpand(),this.focus()):this.parent&&this.parent.parent&&this.parent.focus();break;case 39:!this.bExpanded&&(this.childList||this.data.isLazy)?(this.toggleExpand(),this.focus()):this.childList&&this.childList[0].focus();break;case 38:n=this.getPrevSibling();while(n&&n.bExpanded&&n.childList)n=n.childList[n.childList.length-1];!n&&this.parent&&this.parent.parent&&(n=this.parent),n&&n.focus();break;case 40:if(this.bExpanded&&this.childList)n=this.childList[0];else{var r=this._parentList(!1,!0);for(var i=r.length-1;i>=0;i--){n=r[i].getNextSibling();if(n)break}}n&&n.focus();break;default:t=!1}t&&e.preventDefault()},_onKeypress:function(e){},_onFocus:function(e){var t=this.tree.options;if(e.type=="blur"||e.type=="focusout")t.onBlur&&t.onBlur.call(this.tree,this),this.tree.tnFocused&&$(this.tree.tnFocused.span).removeClass(t.classNames.focused),this.tree.tnFocused=null,t.persist&&$.cookie(t.cookieId+"-focus","",t.cookie);else if(e.type=="focus"||e.type=="focusin")this.tree.tnFocused&&this.tree.tnFocused!==this&&(this.tree.logDebug("dtnode.onFocus: out of sync: curFocus: %o",this.tree.tnFocused),$(this.tree.tnFocused.span).removeClass(t.classNames.focused)),this.tree.tnFocused=this,t.onFocus&&t.onFocus.call(this.tree,this),$(this.tree.tnFocused.span).addClass(t.classNames.focused),t.persist&&$.cookie(t.cookieId+"-focus",this.data.key,t.cookie)},visit:function(e,t){var n=!0;if(t===!0){n=e(this);if(n===!1||n=="skip")return n}if(this.childList)for(var r=0,i=this.childList.length;r<i;r++){n=this.childList[r].visit(e,!0);if(n===!1)break}return n},visitParents:function(e,t){if(t&&e(this)===!1)return!1;var n=this.parent;while(n){if(e(n)===!1)return!1;n=n.parent}return!0},remove:function(){if(this===this.tree.root)throw"Cannot remove system root";return this.parent.removeChild(this)},removeChild:function(e){var t=this.childList;if(t.length==1){if(e!==t[0])throw"removeChild: invalid child";return this.removeChildren()}e===this.tree.activeNode&&e.deactivate(),this.tree.options.persist&&(e.bSelected&&this.tree.persistence.clearSelect(e.data.key),e.bExpanded&&this.tree.persistence.clearExpand(e.data.key)),e.removeChildren(!0),this.ul&&this.ul.removeChild(e.li);for(var n=0,r=t.length;n<r;n++)if(t[n]===e){this.childList.splice(n,1);break}},removeChildren:function(e,t){this.tree.logDebug("%s.removeChildren(%o)",this,e);var n=this.tree,r=this.childList;if(r){for(var i=0,s=r.length;i<s;i++){var o=r[i];o===n.activeNode&&!t&&o.deactivate(),this.tree.options.persist&&!t&&(o.bSelected&&this.tree.persistence.clearSelect(o.data.key),o.bExpanded&&this.tree.persistence.clearExpand(o.data.key)),o.removeChildren(!0,t),this.ul&&$("li",$(this.ul)).remove()}this.childList=null}e||(this._isLoading=!1,this.render())},setTitle:function(e){this.fromDict({title:e})},reload:function(e){throw"Use reloadChildren() instead"},reloadChildren:function(e){if(this.parent===null)throw"Use tree.reload() instead";if(!this.data.isLazy)throw"node.reloadChildren() requires lazy nodes.";if(e){var t=this,n="nodeLoaded.dynatree."+this.tree.$tree.attr("id")+"."+this.data.key;this.tree.$tree.bind(n,function(r,i,s){t.tree.$tree.unbind(n),t.tree.logDebug("loaded %o, %o, %o",r,i,s);if(i!==t)throw"got invalid load event";e.call(t.tree,i,s)})}this.removeChildren(),this._loadContent()},_loadKeyPath:function(e,t){var n=this.tree;n.logDebug("%s._loadKeyPath(%s)",this,e);if(e==="")throw"Key path must not be empty";var r=e.split(n.options.keyPathSeparator);if(r[0]==="")throw"Key path must be relative (don't start with '/')";var i=r.shift();if(this.childList)for(var s=0,o=this.childList.length;s<o;s++){var u=this.childList[s];if(u.data.key===i){if(r.length===0)t.call(n,u,"ok");else if(!u.data.isLazy||u.childList!==null&&u.childList!==undefined)t.call(n,u,"loaded"),u._loadKeyPath(r.join(n.options.keyPathSeparator),t);else{n.logDebug("%s._loadKeyPath(%s) -> reloading %s...",this,e,u);var a=this;u.reloadChildren(function(i,s){s?(n.logDebug("%s._loadKeyPath(%s) -> reloaded %s.",i,e,i),t.call(n,u,"loaded"),i._loadKeyPath(r.join(n.options.keyPathSeparator),t)):(n.logWarning("%s._loadKeyPath(%s) -> reloadChildren() failed.",a,e),t.call(n,u,"error"))})}return}}t.call(n,undefined,"notfound",i,r.length===0),n.logWarning("Node not found: "+i);return},resetLazy:function(){if(this.parent===null)throw"Use tree.reload() instead";if(!this.data.isLazy)throw"node.resetLazy() requires lazy nodes.";this.expand(!1),this.removeChildren()},_addChildNode:function(e,t){var n=this.tree,r=n.options,i=n.persistence;e.parent=this,this.childList===null?this.childList=[]:t||this.childList.length>0&&$(this.childList[this.childList.length-1].span).removeClass(r.classNames.lastsib);if(t){var s=$.inArray(t,this.childList);if(s<0)throw"<beforeNode> must be a child of <this>";this.childList.splice(s,0,e)}else this.childList.push(e);var o=n.isInitializing();r.persist&&i.cookiesFound&&o?(i.activeKey===e.data.key&&(n.activeNode=e),i.focusedKey===e.data.key&&(n.focusNode=e),e.bExpanded=$.inArray(e.data.key,i.expandedKeyList)>=0,e.bSelected=$.inArray(e.data.key,i.selectedKeyList)>=0):(e.data.activate&&(n.activeNode=e,r.persist&&(i.activeKey=e.data.key)),e.data.focus&&(n.focusNode=e,r.persist&&(i.focusedKey=e.data.key)),e.bExpanded=e.data.expand===!0,e.bExpanded&&r.persist&&i.addExpand(e.data.key),e.bSelected=e.data.select===!0,e.bSelected&&r.persist&&i.addSelect(e.data.key)),r.minExpandLevel>=e.getLevel()&&(this.bExpanded=!0);if(e.bSelected&&r.selectMode==3){var u=this;while(u)u.hasSubSel||u._setSubSel(!0),u=u.parent}return n.bEnableUpdate&&this.render(),e},addChild:function(e,t){if(typeof e=="string")throw"Invalid data type for "+e;if(!e||e.length===0)return;if(e instanceof DynaTreeNode)return this._addChildNode(e,t);e.length||(e=[e]);var n=this.tree.enableUpdate(!1),r=null;for(var i=0,s=e.length;i<s;i++){var o=e[i],u=this._addChildNode(new DynaTreeNode(this,this.tree,o),t);r||(r=u),o.children&&u.addChild(o.children,null)}return this.tree.enableUpdate(n),r},append:function(e){return this.tree.logWarning("node.append() is deprecated (use node.addChild() instead)."),this.addChild(e,null)},appendAjax:function(e){var t=this;this.removeChildren(!1,!0),this.setLazyNodeStatus(DTNodeStatus_Loading);if(e.debugLazyDelay){var n=e.debugLazyDelay;e.debugLazyDelay=0,this.tree.logInfo("appendAjax: waiting for debugLazyDelay "+n),setTimeout(function(){t.appendAjax(e)},n);return}var r=e.success,i=e.error,s="nodeLoaded.dynatree."+this.tree.$tree.attr("id")+"."+this.data.key,o=$.extend({},this.tree.options.ajaxDefaults,e,{success:function(e,n,i){var u=t.tree.phase;t.tree.phase="init",o.postProcess?e=o.postProcess.call(this,e,this.dataType):e&&e.hasOwnProperty("d")&&(e=typeof e.d=="string"?$.parseJSON(e.d):e.d),(!$.isArray(e)||e.length!==0)&&t.addChild(e,null),t.tree.phase="postInit",r&&r.call(o,t,e,n),t.tree.logDebug("trigger "+s),t.tree.$tree.trigger(s,[t,!0]),t.tree.phase=u,t.setLazyNodeStatus(DTNodeStatus_Ok),$.isArray(e)&&e.length===0&&(t.childList=[],t.render())},error:function(e,n,r){t.tree.logWarning("appendAjax failed:",n,":\n",e,"\n",r),i&&i.call(o,t,e,n,r),t.tree.$tree.trigger(s,[t,!1]),t.setLazyNodeStatus(DTNodeStatus_Error,{info:n,tooltip:""+r})}});$.ajax(o)},move:function(e,t){var n;if(this===e)return;if(!this.parent)throw"Cannot move system root";if(t===undefined||t=="over")t="child";var r=this.parent,i=t==="child"?e:e.parent;if(i.isDescendantOf(this))throw"Cannot move a node to it's own descendant";if(this.parent.childList.length==1)this.parent.childList=this.parent.data.isLazy?[]:null,this.parent.bExpanded=!1;else{n=$.inArray(this,this.parent.childList);if(n<0)throw"Internal error";this.parent.childList.splice(n,1)}this.parent.ul&&this.parent.ul.removeChild(this.li),this.parent=i;if(i.hasChildren())switch(t){case"child":i.childList.push(this);break;case"before":n=$.inArray(e,i.childList);if(n<0)throw"Internal error";i.childList.splice(n,0,this);break;case"after":n=$.inArray(e,i.childList);if(n<0)throw"Internal error";i.childList.splice(n+1,0,this);break;default:throw"Invalid mode "+t}else i.childList=[this];i.ul||(i.ul=document.createElement("ul"),i.ul.style.display="none",i.li.appendChild(i.ul)),this.li&&i.ul.appendChild(this.li);if(this.tree!==e.tree)throw this.visit(function(t){t.tree=e.tree},null,!0),"Not yet implemented.";r.isDescendantOf(i)||r.render(),i.isDescendantOf(r)||i.render()},lastentry:undefined};var DynaTreeStatus=Class.create();DynaTreeStatus._getTreePersistData=function(e,t){var n=new DynaTreeStatus(e,t);return n.read(),n.toDict()},getDynaTreePersistData=DynaTreeStatus._getTreePersistData,DynaTreeStatus.prototype={initialize:function(e,t){e===undefined&&(e=$.ui.dynatree.prototype.options.cookieId),t=$.extend({},$.ui.dynatree.prototype.options.cookie,t),this.cookieId=e,this.cookieOpts=t,this.cookiesFound=undefined,this.activeKey=null,this.focusedKey=null,this.expandedKeyList=null,this.selectedKeyList=null},_log:function(e){Array.prototype.unshift.apply(arguments,["debug"]),_log.apply(this,arguments)},read:function(){this.cookiesFound=!1;var e=$.cookie(this.cookieId+"-active");this.activeKey=e===null?"":e,e!==null&&(this.cookiesFound=!0),e=$.cookie(this.cookieId+"-focus"),this.focusedKey=e===null?"":e,e!==null&&(this.cookiesFound=!0),e=$.cookie(this.cookieId+"-expand"),this.expandedKeyList=e===null?[]:e.split(","),e!==null&&(this.cookiesFound=!0),e=$.cookie(this.cookieId+"-select"),this.selectedKeyList=e===null?[]:e.split(","),e!==null&&(this.cookiesFound=!0)},write:function(){$.cookie(this.cookieId+"-active",this.activeKey===null?"":this.activeKey,this.cookieOpts),$.cookie(this.cookieId+"-focus",this.focusedKey===null?"":this.focusedKey,this.cookieOpts),$.cookie(this.cookieId+"-expand",this.expandedKeyList===null?"":this.expandedKeyList.join(","),this.cookieOpts),$.cookie(this.cookieId+"-select",this.selectedKeyList===null?"":this.selectedKeyList.join(","),this.cookieOpts)},addExpand:function(e){$.inArray(e,this.expandedKeyList)<0&&(this.expandedKeyList.push(e),$.cookie(this.cookieId+"-expand",this.expandedKeyList.join(","),this.cookieOpts))},clearExpand:function(e){var t=$.inArray(e,this.expandedKeyList);t>=0&&(this.expandedKeyList.splice(t,1),$.cookie(this.cookieId+"-expand",this.expandedKeyList.join(","),this.cookieOpts))},addSelect:function(e){$.inArray(e,this.selectedKeyList)<0&&(this.selectedKeyList.push(e),$.cookie(this.cookieId+"-select",this.selectedKeyList.join(","),this.cookieOpts))},clearSelect:function(e){var t=$.inArray(e,this.selectedKeyList);t>=0&&(this.selectedKeyList.splice(t,1),$.cookie(this.cookieId+"-select",this.selectedKeyList.join(","),this.cookieOpts))},isReloading:function(){return this.cookiesFound===!0},toDict:function(){return{cookiesFound:this.cookiesFound,activeKey:this.activeKey,focusedKey:this.activeKey,expandedKeyList:this.expandedKeyList,selectedKeyList:this.selectedKeyList}},lastentry:undefined};var DynaTree=Class.create();DynaTree.version="$Version:$",DynaTree.prototype={initialize:function(e){this.phase="init",this.$widget=e,this.options=e.options,this.$tree=e.element,this.timer=null,this.divTree=this.$tree.get(0),_initDragAndDrop(this)},_load:function(e){var t=this.$widget,n=this.options,r=this;this.bEnableUpdate=!0,this._nodeCount=1,this.activeNode=null,this.focusNode=null,n.rootVisible!==undefined&&this.logWarning("Option 'rootVisible' is no longer supported."),n.minExpandLevel<1&&(this.logWarning("Option 'minExpandLevel' must be >= 1."),n.minExpandLevel=1),n.classNames!==$.ui.dynatree.prototype.options.classNames&&(n.classNames=$.extend({},$.ui.dynatree.prototype.options.classNames,n.classNames)),n.ajaxDefaults!==$.ui.dynatree.prototype.options.ajaxDefaults&&(n.ajaxDefaults=$.extend({},$.ui.dynatree.prototype.options.ajaxDefaults,n.ajaxDefaults)),n.dnd!==$.ui.dynatree.prototype.options.dnd&&(n.dnd=$.extend({},$.ui.dynatree.prototype.options.dnd,n.dnd)),n.imagePath||$("script").each(function(){var e=/.*dynatree[^\/]*\.js$/i;if(this.src.search(e)>=0)return this.src.indexOf("/")>=0?n.imagePath=this.src.slice(0,this.src.lastIndexOf("/"))+"/skin/":n.imagePath="skin/",r.logDebug("Guessing imagePath from '%s': '%s'",this.src,n.imagePath),!1}),this.persistence=new DynaTreeStatus(n.cookieId,n.cookie),n.persist&&($.cookie||_log("warn","Please include jquery.cookie.js to use persistence."),this.persistence.read()),this.logDebug("DynaTree.persistence: %o",this.persistence.toDict()),this.cache={tagEmpty:"<span class='"+n.classNames.empty+"'></span>",tagVline:"<span class='"+n.classNames.vline+"'></span>",tagExpander:"<span class='"+n.classNames.expander+"'></span>",tagConnector:"<span class='"+n.classNames.connector+"'></span>",tagNodeIcon:"<span class='"+n.classNames.nodeIcon+"'></span>",tagCheckbox:"<span class='"+n.classNames.checkbox+"'></span>",lastentry:undefined},(n.children||n.initAjax&&n.initAjax.url||n.initId)&&$(this.divTree).empty();var i=this.$tree.find(">ul:first").hide();this.tnRoot=new DynaTreeNode(null,this,{}),this.tnRoot.bExpanded=!0,this.tnRoot.render(),this.divTree.appendChild(this.tnRoot.ul);var s=this.tnRoot,o=n.persist&&this.persistence.isReloading(),u=!1,a=this.enableUpdate(!1);this.logDebug("Dynatree._load(): read tree structure..."),n.children?s.addChild(n.children):n.initAjax&&n.initAjax.url?(u=!0,s.data.isLazy=!0,this._reloadAjax(e)):n.initId?this._createFromTag(s,$("#"+n.initId)):(this._createFromTag(s,i),i.remove()),this._checkConsistency(),!u&&n.selectMode==3&&s._updatePartSelectionState(),this.logDebug("Dynatree._load(): render nodes..."),this.enableUpdate(a),this.logDebug("Dynatree._load(): bind events..."),this.$widget.bind(),this.logDebug("Dynatree._load(): postInit..."),this.phase="postInit",n.persist&&this.persistence.write(),this.focusNode&&this.focusNode.isVisible()&&(this.logDebug("Focus on init: %o",this.focusNode),this.focusNode.focus()),u||(n.onPostInit&&n.onPostInit.call(this,o,!1),e&&e.call(this,"ok")),this.phase="idle"},_reloadAjax:function(e){var t=this.options;if(!t.initAjax||!t.initAjax.url)throw"tree.reload() requires 'initAjax' mode.";var n=this.persistence,r=$.extend({},t.initAjax);r.addActiveKey&&(r.data.activeKey=n.activeKey),r.addFocusedKey&&(r.data.focusedKey=n.focusedKey),r.addExpandedKeyList&&(r.data.expandedKeyList=n.expandedKeyList.join(",")),r.addSelectedKeyList&&(r.data.selectedKeyList=n.selectedKeyList.join(",")),r.success&&this.logWarning("initAjax: success callback is ignored; use onPostInit instead."),r.error&&this.logWarning("initAjax: error callback is ignored; use onPostInit instead.");var i=n.isReloading();r.success=function(n,r,s){t.selectMode==3&&n.tree.tnRoot._updatePartSelectionState(),t.onPostInit&&t.onPostInit.call(n.tree,i,!1),e&&e.call(n.tree,"ok")},r.error=function(n,r,s,o){t.onPostInit&&t.onPostInit.call(n.tree,i,!0,r,s,o),e&&e.call(n.tree,"error",r,s,o)},this.logDebug("Dynatree._init(): send Ajax request..."),this.tnRoot.appendAjax(r)},toString:function(){return"Dynatree '"+this.$tree.attr("id")+"'"},toDict:function(){return this.tnRoot.toDict(!0)},serializeArray:function(e){var t=this.getSelectedNodes(e),n=this.$tree.attr("name")||this.$tree.attr("id"),r=[];for(var i=0,s=t.length;i<s;i++)r.push({name:n,value:t[i].data.key});return r},getPersistData:function(){return this.persistence.toDict()},logDebug:function(e){this.options.debugLevel>=2&&(Array.prototype.unshift.apply(arguments,["debug"]),_log.apply(this,arguments))},logInfo:function(e){this.options.debugLevel>=1&&(Array.prototype.unshift.apply(arguments,["info"]),_log.apply(this,arguments))},logWarning:function(e){Array.prototype.unshift.apply(arguments,["warn"]),_log.apply(this,arguments)},isInitializing:function(){return this.phase=="init"||this.phase=="postInit"},isReloading:function(){return(this.phase=="init"||this.phase=="postInit")&&this.options.persist&&this.persistence.cookiesFound},isUserEvent:function(){return this.phase=="userEvent"},redraw:function(){this.tnRoot.render(!1,!1)},renderInvisibleNodes:function(){this.tnRoot.render(!1,!0)},reload:function(e){this._load(e)},getRoot:function(){return this.tnRoot},enable:function(){this.$widget.enable()},disable:function(){this.$widget.disable()},getNodeByKey:function(e){var t=document.getElementById(this.options.idPrefix+e);if(t)return t.dtnode?t.dtnode:null;var n=null;return this.visit(function(t){if(t.data.key===e)return n=t,!1},!0),n},getActiveNode:function(){return this.activeNode},reactivate:function(e){var t=this.activeNode;t&&(this.activeNode=null,t.activate(),e&&t.focus())},getSelectedNodes:function(e){var t=[];return this.tnRoot.visit(function(n){if(n.bSelected){t.push(n);if(e===!0)return"skip"}}),t},activateKey:function(e){var t=e===null?null:this.getNodeByKey(e);return t?(t.focus(),t.activate(),t):(this.activeNode&&this.activeNode.deactivate(),this.activeNode=null,null)},loadKeyPath:function(e,t){var n=e.split(this.options.keyPathSeparator);return n[0]===""&&n.shift(),n[0]==this.tnRoot.data.key&&(this.logDebug("Removed leading root key."),n.shift()),e=n.join(this.options.keyPathSeparator),this.tnRoot._loadKeyPath(e,t)},selectKey:function(e,t){var n=this.getNodeByKey(e);return n?(n.select(t),n):null},enableUpdate:function(e){return this.bEnableUpdate==e?e:(this.bEnableUpdate=e,e&&this.redraw(),!e)},count:function(){return this.tnRoot.countChildren()},visit:function(e,t){return this.tnRoot.visit(e,t)},_createFromTag:function(parentTreeNode,$ulParent){var self=this;$ulParent.find(">li").each(function(){var $li=$(this),$liSpan=$li.find(">span:first"),$liA=$li.find(">a:first"),title,href=null,target=null,tooltip;if($liSpan.length)title=$liSpan.html();else if($liA.length)title=$liA.html(),href=$liA.attr("href"),target=$liA.attr("target"),tooltip=$liA.attr("title");else{title=$li.html();var iPos=title.search(/<ul/i);iPos>=0?title=$.trim(title.substring(0,iPos)):title=$.trim(title)}var data={title:title,tooltip:tooltip,isFolder:$li.hasClass("folder"),isLazy:$li.hasClass("lazy"),expand:$li.hasClass("expanded"),select:$li.hasClass("selected"),activate:$li.hasClass("active"),focus:$li.hasClass("focused"),noLink:$li.hasClass("noLink")};href&&(data.href=href,data.target=target),$li.attr("title")&&(data.tooltip=$li.attr("title")),$li.attr("id")&&(data.key=""+$li.attr("id"));if($li.attr("data")){var dataAttr=$.trim($li.attr("data"));if(dataAttr){dataAttr.charAt(0)!="{"&&(dataAttr="{"+dataAttr+"}");try{$.extend(data,eval("("+dataAttr+")"))}catch(e){throw"Error parsing node data: "+e+"\ndata:\n'"+dataAttr+"'"}}}var childNode=parentTreeNode.addChild(data),$ul=$li.find(">ul:first");$ul.length&&self._createFromTag(childNode,$ul)})},_checkConsistency:function(){},_setDndStatus:function(e,t,n,r,i){var s=e?$(e.span):null,o=$(t.span);this.$dndMarker||(this.$dndMarker=$("<div id='dynatree-drop-marker'></div>").hide().css({"z-index":1e3}).prependTo($(this.divTree).parent()));if(r==="after"||r==="before"||r==="over"){var u="0 0";switch(r){case"before":this.$dndMarker.removeClass("dynatree-drop-after dynatree-drop-over"),this.$dndMarker.addClass("dynatree-drop-before"),u="0 -8";break;case"after":this.$dndMarker.removeClass("dynatree-drop-before dynatree-drop-over"),this.$dndMarker.addClass("dynatree-drop-after"),u="0 8";break;default:this.$dndMarker.removeClass("dynatree-drop-after dynatree-drop-before"),this.$dndMarker.addClass("dynatree-drop-over"),o.addClass("dynatree-drop-target"),u="8 0"}this.$dndMarker.show().position({my:"left top",at:"left top",of:o,offset:u})}else o.removeClass("dynatree-drop-target"),this.$dndMarker.hide();r==="after"?o.addClass("dynatree-drop-after"):o.removeClass("dynatree-drop-after"),r==="before"?o.addClass("dynatree-drop-before"):o.removeClass("dynatree-drop-before"),i===!0?(s&&s.addClass("dynatree-drop-accept"),o.addClass("dynatree-drop-accept"),n.addClass("dynatree-drop-accept")):(s&&s.removeClass("dynatree-drop-accept"),o.removeClass("dynatree-drop-accept"),n.removeClass("dynatree-drop-accept")),i===!1?(s&&s.addClass("dynatree-drop-reject"),o.addClass("dynatree-drop-reject"),n.addClass("dynatree-drop-reject")):(s&&s.removeClass("dynatree-drop-reject"),o.removeClass("dynatree-drop-reject"),n.removeClass("dynatree-drop-reject"))},_onDragEvent:function(e,t,n,r,i,s){var o=this.options,u=this.options.dnd,a=null,f=$(t.span),l,c;switch(e){case"helper":var h=$("<div class='dynatree-drag-helper'><span class='dynatree-drag-helper-img' /></div>").append($(r.target).closest(".dynatree-title").clone());$("ul.dynatree-container",t.tree.divTree).append(h),h.data("dtSourceNode",t),a=h;break;case"start":t.isStatusNode()?a=!1:u.onDragStart&&(a=u.onDragStart(t)),a===!1?(this.logDebug("tree.onDragStart() cancelled"),i.helper.trigger("mouseup"),i.helper.hide()):f.addClass("dynatree-drag-source");break;case"enter":a=u.onDragEnter?u.onDragEnter(t,n):null,a?a={over:a===!0||a==="over"||$.inArray("over",a)>=0,before:a===!0||a==="before"||$.inArray("before",a)>=0,after:a===!0||a==="after"||$.inArray("after",a)>=0}:a=!1,i.helper.data("enterResponse",a);break;case"over":c=i.helper.data("enterResponse"),l=null;if(c!==!1)if(typeof c=="string")l=c;else{var p=f.offset(),d={x:r.pageX-p.left,y:r.pageY-p.top},v={x:d.x/f.width(),y:d.y/f.height()};c.after&&v.y>.75?l="after":!c.over&&c.after&&v.y>.5?l="after":c.before&&v.y<=.25?l="before":!c.over&&c.before&&v.y<=.5?l="before":c.over&&(l="over"),u.preventVoidMoves&&(t===n?l=null:l==="before"&&n&&t===n.getNextSibling()?l=null:l==="after"&&n&&t===n.getPrevSibling()?l=null:l==="over"&&n&&n.parent===t&&n.isLastSibling()&&(l=null)),i.helper.data("hitMode",l)}l==="over"&&u.autoExpandMS&&t.hasChildren()!==!1&&!t.bExpanded&&t.scheduleAction("expand",u.autoExpandMS);if(l&&u.onDragOver){a=u.onDragOver(t,n,l);if(a==="over"||a==="before"||a==="after")l=a}this._setDndStatus(n,t,i.helper,l,a!==!1&&l!==null);break;case"drop":var m=i.helper.hasClass("dynatree-drop-reject");l=i.helper.data("hitMode"),l&&u.onDrop&&!m&&u.onDrop(t,n,l,i,s);break;case"leave":t.scheduleAction("cancel"),i.helper.data("enterResponse",null),i.helper.data("hitMode",null),this._setDndStatus(n,t,i.helper,"out",undefined),u.onDragLeave&&u.onDragLeave(t,n);break;case"stop":f.removeClass("dynatree-drag-source"),u.onDragStop&&u.onDragStop(t);break;default:throw"Unsupported drag event: "+e}return a},cancelDrag:function(){var e=$.ui.ddmanager.current;e&&e.cancel()},lastentry:undefined},$.widget("ui.dynatree",{_init:function(){if(versionCompare($.ui.version,"1.8")<0)return this.options.debugLevel>=0&&_log("warn","ui.dynatree._init() was called; you should upgrade to jquery.ui.core.js v1.8 or higher."),this._create();this.options.debugLevel>=2&&_log("debug","ui.dynatree._init() was called; no current default functionality.")},_create:function(){var e=this.options;e.debugLevel>=1&&logMsg("Dynatree._create(): version='%s', debugLevel=%o.",$.ui.dynatree.version,this.options.debugLevel),this.options.event+=".dynatree";var t=this.element.get(0);this.tree=new DynaTree(this),this.tree._load(),this.tree.logDebug("Dynatree._init(): done.")},bind:function(){function t(e){e=$.event.fix(e||window.event);var t=$.ui.dynatree.getNode(e.target);return t?t._onFocus(e):!1}this.unbind();var e="click.dynatree dblclick.dynatree";this.options.keyboard&&(e+=" keypress.dynatree keydown.dynatree"),this.element.bind(e,function(e){var t=$.ui.dynatree.getNode(e.target);if(!t)return!0;var n=t.tree,r=n.options;n.logDebug("event(%s): dtnode: %s",e.type,t);var i=n.phase;n.phase="userEvent";try{switch(e.type){case"click":return r.onClick&&r.onClick.call(n,t,e)===!1?!1:t._onClick(e);case"dblclick":return r.onDblClick&&r.onDblClick.call(n,t,e)===!1?!1:t._onDblClick(e);case"keydown":return r.onKeydown&&r.onKeydown.call(n,t,e)===!1?!1:t._onKeydown(e);case"keypress":return r.onKeypress&&r.onKeypress.call(n,t,e)===!1?!1:t._onKeypress(e)}}catch(s){var o=null;n.logWarning("bind(%o): dtnode: %o, error: %o",e,t,s)}finally{n.phase=i}});var n=this.tree.divTree;n.addEventListener?(n.addEventListener("focus",t,!0),n.addEventListener("blur",t,!0)):n.onfocusin=n.onfocusout=t},unbind:function(){this.element.unbind(".dynatree")},enable:function(){this.bind(),$.Widget.prototype.enable.apply(this,arguments)},disable:function(){this.unbind(),$.Widget.prototype.disable.apply(this,arguments)},getTree:function(){return this.tree},getRoot:function(){return this.tree.getRoot()},getActiveNode:function(){return this.tree.getActiveNode()},getSelectedNodes:function(){return this.tree.getSelectedNodes()},lastentry:undefined}),versionCompare($.ui.version,"1.8")<0&&($.ui.dynatree.getter="getTree getRoot getActiveNode getSelectedNodes"),$.ui.dynatree.version="$Version:$",$.ui.dynatree.getNode=function(e){if(e instanceof DynaTreeNode)return e;e.selector!==undefined&&(e=e[0]);while(e){if(e.dtnode)return e.dtnode;e=e.parentNode}return null},$.ui.dynatree.getPersistData=DynaTreeStatus._getTreePersistData,$.ui.dynatree.prototype.options={title:"Dynatree",minExpandLevel:1,imagePath:null,children:null,initId:null,initAjax:null,autoFocus:!0,keyboard:!0,persist:!1,autoCollapse:!1,clickFolderMode:3,activeVisible:!0,checkbox:!1,selectMode:2,fx:null,noLink:!1,onClick:null,onDblClick:null,onKeydown:null,onKeypress:null,onFocus:null,onBlur:null,onQueryActivate:null,onQuerySelect:null,onQueryExpand:null,onPostInit:null,onActivate:null,onDeactivate:null,onSelect:null,onExpand:null,onLazyRead:null,onCustomRender:null,onCreate:null,onRender:null,postProcess:null,dnd:{onDragStart:null,onDragStop:null,autoExpandMS:1e3,preventVoidMoves:!0,onDragEnter:null,onDragOver:null,onDrop:null,onDragLeave:null},ajaxDefaults:{cache:!1,timeout:0,dataType:"json"},strings:{loading:"Loading…",loadError:"Load error!"},generateIds:!1,idPrefix:"dynatree-id-",keyPathSeparator:"/",cookieId:"dynatree",cookie:{expires:null},classNames:{container:"dynatree-container",node:"dynatree-node",folder:"dynatree-folder",empty:"dynatree-empty",vline:"dynatree-vline",expander:"dynatree-expander",connector:"dynatree-connector",checkbox:"dynatree-checkbox",nodeIcon:"dynatree-icon",title:"dynatree-title",noConnector:"dynatree-no-connector",nodeError:"dynatree-statusnode-error",nodeWait:"dynatree-statusnode-wait",hidden:"dynatree-hidden",combinedExpanderPrefix:"dynatree-exp-",combinedIconPrefix:"dynatree-ico-",nodeLoading:"dynatree-loading",hasChildren:"dynatree-has-children",active:"dynatree-active",selected:"dynatree-selected",expanded:"dynatree-expanded",lazy:"dynatree-lazy",focused:"dynatree-focused",partsel:"dynatree-partsel",lastsib:"dynatree-lastsib"},debugLevel:2,lastentry:undefined},versionCompare($.ui.version,"1.8")<0&&($.ui.dynatree.defaults=$.ui.dynatree.prototype.options),$.ui.dynatree.nodedatadefaults={title:null,key:null,isFolder:!1,isLazy:!1,tooltip:null,href:null,icon:null,addClass:null,noLink:!1,activate:!1,focus:!1,expand:!1,select:!1,hideCheckbox:!1,unselectable:!1,children:null,lastentry:undefined};var didRegisterDnd=!1,_registerDnd=function(){if(didRegisterDnd)return;$.ui.plugin.add("draggable","connectToDynatree",{start:function(e,t){var n=$(this).data("ui-draggable")||$(this).data("draggable"),r=t.helper.data("dtSourceNode")||null;if(r)return n.offset.click.top=-2,n.offset.click.left=16,r.tree._onDragEvent("start",r,null,e,t,n)},drag:function(e,t){var n=$(this).data("ui-draggable")||$(this).data("draggable"),r=t.helper.data("dtSourceNode")||null,i=t.helper.data("dtTargetNode")||null,s=$.ui.dynatree.getNode(e.target);if(e.target&&!s){var o=$(e.target).closest("div.dynatree-drag-helper,#dynatree-drop-marker").length>0;if(o)return}t.helper.data("dtTargetNode",s),i&&i!==s&&i.tree._onDragEvent("leave",i,r,e,t,n),s&&(!s.tree.options.dnd.onDrop||(s===i?s.tree._onDragEvent("over",s,r,e,t,n):s.tree._onDragEvent("enter",s,r,e,t,n)))},stop:function(e,t){var n=$(this).data("ui-draggable")||$(this).data("draggable"),r=t.helper.data("dtSourceNode")||null,i=t.helper.data("dtTargetNode")||null,s=n._mouseDownEvent,o=e.type,u=o=="mouseup"&&e.which==1;logMsg("draggable-connectToDynatree.stop: targetNode(from event): %s, dtTargetNode: %s",i,t.helper.data("dtTargetNode")),u||logMsg("Drag was cancelled"),i&&(u&&i.tree._onDragEvent("drop",i,r,e,t,n),i.tree._onDragEvent("leave",i,r,e,t,n)),r&&r.tree._onDragEvent("stop",r,null,e,t,n)}}),didRegisterDnd=!0}})(jQuery);
11326 /**
11327  *  KKUsersManagerWidget
11328  * @constructor
11329  */   
11330 function KKAdminUsersManagerWidget(instanceId, data){
11331     
11332     this.loader=function(){
11333         var dataR = DATA.getRemote("kk_userAdmin", "", NOT_READY, POLL_RATES.VERY_FAST);  //, NOT_READY, POLL_RATES.SLOW
11334         var groupsR = DATA.getRemote("aurora_groups", "", NOT_READY, POLL_RATES.VERY_FAST); //, NOT_READY, POLL_RATES.SLOW
11335         var renderedTableB = F.liftBI(function(data, groups){
11336             if(data==NOT_READY||groups==NOT_READY)
11337                 return NOT_READY;
11338             for(colIndex in data["COLUMNS"]){
11339                 if(data["COLUMNS"][colIndex]["reference"]=="group"){
11340                     if(data["COLUMNMETADATA"][colIndex]==undefined)
11341                         data["COLUMNMETADATA"][colIndex] = {};
11342                     data["COLUMNMETADATA"][colIndex]["renderer"] = new AuroraUserGroupColumn(groups["DATA"]);
11343                 }
11344             
11345             }
11346             //showObj(data);
11347             return data;
11348         },function(value){
11349             return [value, null];
11350         }, dataR.behaviour, groupsR.behaviour);
11351     
11352     tableB = TableWidgetB(instanceId+"_table", data, renderedTableB);    
11353     F.insertDomB(tableB, instanceId+"_container");
11354     
11355     }
11356     this.destroy=function(){
11357         DATA.deregister("kk_userAdmin", "");
11358         DATA.deregister("aurora_groups", "");
11359     }
11360     this.build=function(){
11361         return "<span id=\""+instanceId+"_container\"> </span>";
11362     }
11363 }
11364 WIDGETS.register("KKAdminUsersManagerWidget", KKAdminUsersManagerWidget);  
11365 
11366 
11367 function SchoolManagementWidget(instanceId, data){       
11368 	this.loader=function(){
11369 		   var schoolsAdminR = DATA.getRemote("konfidentkidz_allSchools", "", NOT_READY, POLL_RATES.VERY_FAST);  //, NOT_READY, POLL_RATES.SLOW
11370 	        var renderedTableB = F.liftBI(function(data){
11371 	            if(data==NOT_READY){
11372 	                return NOT_READY;
11373 	            }
11374 	            return data;
11375 	        },function(value){
11376 	            return [value];
11377 	        }, schoolsAdminR.behaviour);
11378 	    
11379 	    tableB = TableWidgetB(instanceId+"_table", data, renderedTableB);    
11380 	    F.insertDomB(tableB, instanceId+"_container");
11381 	    
11382     }    
11383     this.build=function(){
11384     	return "<div id=\""+instanceId+"_container\">Loading</div>";
11385     }
11386     this.destroy=function(){
11387     }
11388 }
11389 
11390 WIDGETS.register("SchoolManagementWidget", SchoolManagementWidget);
11391 
11392 
11393 
11394 
11395 
11396 
11397 
11398 function SeminarSelectionField(instanceId, data){;
11399     this.instanceId = instanceId;
11400     var targetId = data.targetId;
11401     this.loader=function(){    
11402         var table = DOM.get(targetId);
11403         if(table==undefined){
11404         	return;
11405         }
11406         var lastTitle = "";
11407         for (var i = 0, row; row = table.rows[i]; i++) {
11408             var text = (row.cells[1].textContent || row.cells[1].innerText || "").trim();
11409             var title = (row.cells[0].textContent || row.cells[0].innerText || "").trim();
11410             lastTitle = (title!="")?title:lastTitle;
11411             var optionText = lastTitle+" "+text;
11412             
11413            DOM.get(this.instanceId).appendChild(DOM.createOption(this.instanceId+"_"+index, undefined, optionText, optionText));
11414         }
11415                   
11416         var valueName = (data.name==undefined)?"Seminar":data.name; 
11417         var formGroupB = DATA.get(data.formGroup, undefined, {}); 
11418         var selectValueB = F.extractValueB(this.instanceId);
11419         var validB = selectValueB.liftB(function(text){      
11420             return DOM.get(instanceId).selectedIndex!=0;
11421         });
11422         var widgetResponseB = F.liftB(function(valid, text){
11423             if(!good()||text==null){
11424                 return NOT_READY;
11425             }
11426           /*  document.getElementById(instanceId).className = (text.length==0)?'':((valid)?'form_validator_validInput':'form_validator_invalidInput');    */
11427             return {value: text, valid: valid, name: valueName};
11428         }, validB, selectValueB);  
11429         
11430         //pushToValidationGroupBehaviour(instanceId, validationGroupB, validB);
11431         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetResponseB);  
11432     }      
11433     this.build=function(){
11434         var select = DOM.create('select');
11435         select.id = this.instanceId;
11436         return select;         
11437     }
11438 } 
11439 
11440 
11441 
11442 
11443 
11444 WIDGETS.register("SeminarSelectionField", SeminarSelectionField); 
11445 function KK_showLicensingTerms(callback){
11446     ajax({
11447         dataType: 'json',
11448         url: SETTINGS.scriptPath+"request/getPage/purchase/onlineterms/",
11449         success: function(data){
11450             var page = data.html;
11451             UI.showMessage("", page, callback, {modal: true,draggable:false, resizable: false, width: "70%", height: 500});
11452         },
11453         error: connectionError
11454     }); 
11455 }
11456 function KK_showPrivacyAgreement(callback){
11457      ajax({
11458         dataType: 'json',
11459         url: SETTINGS.scriptPath+"request/getPage/purchase/privacyagreement/",
11460         success: function(data){
11461             var page = data.html;
11462             UI.showMessage("", page, callback, {modal: true,draggable:false, resizable: false, width: "70%", height: 500});
11463         },
11464         error: connectionError
11465     });
11466 }
11467 function KK_showTermsOfUse(callback){
11468      ajax({
11469         dataType: 'json',
11470         url: SETTINGS.scriptPath+"request/getPage/purchase/termsofuse/",
11471         success: function(data){
11472             var page = data.html;
11473             UI.showMessage("", page, callback, {modal: true,draggable:false, resizable: false, width: "70%", height: 500});
11474         },
11475         error: connectionError
11476     }); 
11477 }
11478 function KK_rowClicked(row){
11479     document.getElementById(row).click();
11480 } 
11481              
11482 /*function PayPalBuyNowWidget(instanceId, data){
11483     var productId = data.productId; //WDFXB2W6XQWPC   
11484     var optionName = data.optionName;//"Number of Students";
11485     var agreeId = data.agreeId;
11486     var formGroup = data.formGroup;   
11487     this.loader=function(){
11488         var userLoggedInB = userB.liftB(function(user){
11489             if(user==NOT_READY)
11490                 return NOT_READY;
11491             document.getElementById("contactTable").style.display = (user.group_id!=1)?'none':'';
11492             return user.group_id!=1;
11493         });
11494         var formGroupB = DATA.get(formGroup, undefined, {});
11495         var groupDataB = formGroupB.liftB(function(validationMap){
11496             return F.liftB.apply(this,[function(){
11497                 var groupData = arguments;
11498                 var dataObject = {};
11499                 var valid = true;
11500                 for(entryIndex in groupData){
11501                     var entry = groupData[entryIndex];
11502                     //log(entry);
11503                     dataObject[entry.name] = entry.value;
11504                     if(!entry.valid){
11505                         valid = false;
11506                     }
11507                 }
11508                 dataObject.valid = valid;
11509                 return dataObject;
11510             }].concat(validationMap));
11511         }).switchB();            
11512         var allValidB = groupDataB.liftB(function(groupData){
11513             if(!good())
11514                 return NOT_READY;
11515             return groupData.valid;
11516         });
11517         var productValidB = formGroupB.liftB(function(validationMap){
11518             return F.liftB.apply(this,[function(){
11519                 for(entryIndex in arguments){
11520                     var entry = arguments[entryIndex];
11521                     if((entry.name=="terms"||entry.name=="product")&&entry.valid==false){
11522                         return false;
11523                     }
11524                 }
11525                 return true;
11526             }].concat(validationMap));
11527         }).switchB();          
11528         var checkedB = F.extractValueB(agreeId);
11529         var targetProductB = jQuery("input:radio[name=numstudents]").fj('extEvtE', 'click').mapE(function(e){
11530             return (e.originalTarget!=undefined)?e.originalTarget:e.target;
11531         }).startsWith(""); 
11532        
11533        
11534        
11535         //F.insertValueB(F.ifB(userLoggedInB, 'none', 'block'),"contactTable", 'style', 'display');
11536    
11537         var buttonClickedE = jQuery("#"+instanceId+"_button").fj('extEvtE', 'click').snapshotE(groupDataB);
11538         var registrationB = getAjaxRequestE(buttonClickedE, "/request/KK_registerUser").mapE(function(data){
11539             return data;
11540         }).startsWith(NOT_READY);  
11541         
11542         F.liftB(function(targetProduct, groupData, registration, loggedInAndProductValid){ 
11543             if(!good)
11544                 return NOT_READY;     
11545             if(loggedInAndProductValid){
11546                 groupData.valid = true;
11547             }                                            
11548             document.getElementById(instanceId+"_button").style.display=(groupData.valid?'block':'none');
11549             if(registration.valid){  //User creation Success
11550                 log("Submiting Form");
11551                 document.getElementById(instanceId+"_optionValue").value = targetProduct.value+" or under";
11552                 document.getElementById(instanceId+"_buttonId").value = productId;
11553                 document.getElementById(instanceId+"_userId").value = registration.userId;                        
11554                 //document.getElementById(instanceId+"_form").submit();
11555             }    
11556         }, targetProductB, groupDataB, registrationB, F.andB(productValidB, userLoggedInB));
11557         
11558         
11559         
11560         var widgetValueB = F.liftB(function(targetProduct){
11561             return {valid: (targetProduct!=""), value: productId, name: "product"};
11562         }, targetProductB); 
11563         
11564         var productOptionB = F.liftB(function(targetProduct){
11565             return {valid: (targetProduct!=""), value: targetProduct.value, name: "productoption"};
11566         }, targetProductB);
11567         
11568         var termsAcceptedB = F.liftB(function(checked){
11569             return {valid: (checked||checked=="true"), value: checked, name: "terms"};
11570         }, checkedB); 
11571         
11572         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB);
11573         pushToValidationGroupBehaviour(instanceId, formGroupB, productOptionB);
11574         pushToValidationGroupBehaviour(instanceId, formGroupB, termsAcceptedB); 
11575     }
11576     this.build=function(){
11577         var optionValue = ""; //100 Students or Under         //target=\"paypal\" 
11578         return "<form id=\""+instanceId+"_form\" action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\" accept-charset=\"UTF-8\" style=\"display: none;\">"+
11579 "<input type=\"hidden\" name=\"cmd\" value=\"_s-xclick\">"+
11580 "<input type=\"hidden\" name=\"hosted_button_id\" id=\""+instanceId+"_buttonId\" value=\"\">"+
11581 "<table>"+
11582 "<tr><td><input id=\""+instanceId+"_userId\" type=\"hidden\" name=\"userId\" value=\"\"><input type=\"hidden\" name=\"on0\" value=\"Number of Students\"><input id=\""+instanceId+"_optionValue\" type=\"hidden\" name=\"os0\" value=\"100 or under\">Number of Students</td></tr><tr><td> </td></tr>"+
11583 "</table>"+
11584 "<input type=\"hidden\" name=\"currency_code\" value=\"NZD\">"+
11585 "<input type=\"image\" src=\"/themes/konfidentkidz/purchasenow.png\" border=\"0\" name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\">"+
11586 "<img alt=\"\" border=\"0\" src=\"https://www.paypalobjects.com/en_US/i/scr/pixel.gif\" width=\"1\" height=\"1\">"+
11587 "</form>"+
11588 "<span id=\""+instanceId+"_button\" style=\"display: none;margin: 0 auto; margin-top: 10px; \" class=\"button\">Purchase Now</span>";
11589     }
11590     this.destroy=function(){
11591     }                                                    
11592 }  */  
11593 /**
11594  *  ProductSelectionWidgetConfigurator
11595  * @constructor
11596  */                                                      
11597 /*function PayPalBuyNowWidgetConfigurator(){
11598     var id = "PayPalBuyNowWidgetConfigurator";
11599     this['load'] = function(newData){}
11600     this['build'] = function(newData){
11601         var productId = "";
11602         var optionName = ""; 
11603         var agreeId = "";
11604         if(newData!=undefined){
11605             productId = newData['productId'];
11606             optionName = newData['optionName']; 
11607             agreeId = newData['agreeId'];   
11608         }
11609         return "Product Id: <input type=\"text\" id=\""+id+"_productId\" value=\""+productId+"\" /><br />"+
11610         "Option Name: <input type=\"text\" id=\""+id+"_optionName\" value=\""+optionName+"\" />"+
11611         "Agree Id: <input type=\"checkbox\" id=\""+id+"_agreeId\" checked=\""+agreeId+"\" />";
11612               
11613         //   productId      optionName
11614     }
11615     this['getData'] = function(){
11616         return {"productId": document.getElementById(id+'_productId').value, "optionName": document.getElementById(id+'_optionName').value, "agreeId":document.getElementById(id+'_agreeId').checked};
11617     }
11618     this['getName'] = function(){
11619         return "PayPay Buy Now Button";
11620     }
11621     this['getDescription'] = function(){
11622         return "A Pay Pal Widget With HTML Option Selector";
11623     }
11624     this['getPackage'] = function(){
11625         return "KonfidentKidz";
11626     }
11627 } 
11628 WIDGETS.register("PayPalBuyNowWidget", PayPalBuyNowWidget, PayPalBuyNowWidgetConfigurator);  */
11629 
11630 function KKSchoolMapWidget(instanceId, data){
11631     var mapW = new GoogleMapWidget(instanceId+"_gmap", data);
11632     this.loader=function(){ 
11633         var dataB = DATA.getRemote("konfidentkidz_myschool").behaviour;
11634         var addressB = dataB.liftB(function(data){
11635             if(!good())
11636                 return NOT_READY;
11637             return data.address;
11638         });
11639         mapW.loader(addressB); 
11640     }
11641     this.build=function(){
11642         return mapW.build();
11643     }
11644     this.destroy=function(){
11645         mapW.destroy();
11646     }
11647 }
11648 WIDGETS.register("KKSchoolMapWidget", KKSchoolMapWidget); 
11649 
11650 function KKSchoolNameWidget(instanceId, data){
11651     var element = document.createElement("span");
11652     element.id = instanceId+"_container";
11653     this.loader=function(){                
11654         var dataB = DATA.getRemote("konfidentkidz_myschool").behaviour;
11655         var addressB = dataB.liftB(function(data){
11656             if(!good())
11657                 return NOT_READY;
11658             document.getElementById(element.id).innerHTML = (data.name==undefined)?"":data.name;
11659         }); 
11660     }
11661     this.build=function(){
11662         return element;
11663     }
11664     this.destroy=function(){
11665     }
11666 }
11667 WIDGETS.register("KKSchoolNameWidget", KKSchoolNameWidget);
11668 
11669 function KKSchoolLogoWidget(instanceId, data){
11670 	var widgetRef = data.widgetRef;
11671 	data.dropHtml = "<img src=\"/resources/kk/schoollogo.png\" alt=\"\" />";
11672 	data.dropHoverHtml = "<img src=\"/resources/kk/schoollogo2.png\" alt=\"\" />";
11673     var imageWidgetW = new UploadableImageWidget(instanceId+"_logo", data);             
11674     this.loader=function(){
11675         var dataB = DATA.getRemote("konfidentkidz_myschool").behaviour;
11676         var newWidgetRefB = F.liftB(function(data){
11677         	if(!good()){
11678         		return NOT_READY;
11679         	}
11680             imageWidgetW.hide();
11681             if(!good())
11682                 return NOT_READY;  
11683             imageWidgetW.show();
11684             return data.school_id+"_"+widgetRef;
11685         }, dataB);
11686         imageWidgetW.loader(newWidgetRefB);    
11687     	
11688     }
11689     this.build=function(){
11690         return imageWidgetW.build();
11691     }
11692     this.destroy=function(){
11693         imageWidgetW.destroy();
11694     }
11695 }
11696 WIDGETS.register("KKSchoolLogoWidget", KKSchoolLogoWidget);
11697 
11698 function KKProductOptions(instanceId, data){  
11699     var id = instanceId+"_cont";       
11700     this.loader=function(){
11701     	
11702     	var termsAcceptedR = DATA.getRemote("konfidentkidz_terms", undefined, NOT_READY, POLL_RATES.NORMAL);
11703     	var termsAcceptedB = termsAcceptedR.behaviour;
11704     	termsAcceptedB.liftB(function(termsAccepted){
11705     		if(!good()){
11706     			return NOT_READY;
11707     		}
11708     		if(!termsAccepted){
11709     			KK_showLicensingTerms(function(){
11710     				KK_showPrivacyAgreement(function(){
11711     					KK_showTermsOfUse(function(){
11712     						 ajax({
11713     						        dataType: 'json',
11714     						        url: SETTINGS.scriptPath+"request/konfidentkidz_acceptterms",
11715     						        success: function(data){
11716     						        },
11717     						        error: function(){}
11718     						    }); 
11719     					});
11720     				});
11721     			});  
11722     		}
11723     	});
11724     	F.insertValueB(F.ifB(termsAcceptedB, 'block', 'none'),DOM.get(id), 'style', 'display');
11725     	
11726         var dataB = DATA.getRemote("konfidentkidz_myproducts", undefined, NOT_READY, POLL_RATES.NORMAL).behaviour;
11727         var productOptionsDivB = F.liftB(function(data){
11728             if(!good())
11729                 return "";
11730             var html="";
11731             for(index in data){
11732                 var product = data[index];
11733                 var img = (data[index].image_src.length==0)?"<h1>"+product.name+"</h1>":"<div style=\"text-align: center;\"><img src=\""+data[index].image_src+"\" class=\"homePosters\" alt=\"\" /></div>";
11734                 html+=img+product.linksHtml;
11735                 html+=product.admin_html;
11736             }      
11737             return DOM.createDiv(undefined, html);
11738         }, dataB);   
11739         F.insertDomB(productOptionsDivB, id);
11740     }
11741     this.build=function(){
11742         return "<div id=\""+id+"\"> </div>";
11743     }
11744     this.destroy=function(){
11745     }
11746 }
11747 
11748 WIDGETS.register("KKProductOptions", KKProductOptions);
11749 
11750 function KKSchoolProducts(instanceId, data){       
11751 	var optionName = "Option 1";
11752 	var productId = "DNMTLPCDXZ8M4";
11753 	this.loader=function(){
11754         F.extractEventE(instanceId+"_button", "click").mapE(function(){
11755         	//DOM.get(instanceId+"_form").submit();
11756         	DOM.get(instanceId+"_frame").src = "/request/KK_addToCart?code="+productId;
11757         }).delayE(1000).mapE(function(){
11758         	DOM.get(instanceId+"_frame").contentWindow.loadPage();
11759         });
11760     }    
11761     this.build=function(){
11762     	
11763     	return ""+
11764     	"<form id=\""+instanceId+"_form\" action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\" style=\"display: none;\">"+
11765     	"<input type=\"hidden\" name=\"cmd\" value=\"_s-xclick\">"+ 
11766     	"<input type=\"hidden\" name=\"hosted_button_id\" value=\""+productId+"\"><input type=\"hidden\" name=\"on0\" value=\"Age Range\"><input type=\"hidden\" name=\"os0\" value=\""+optionName+"\" />"+ 
11767     	"<input type=\"image\" src=\"https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif\" border=\"0\" name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\">"+
11768     	"<img alt=\"\" border=\"0\" src=\"https://www.paypalobjects.com/en_US/i/scr/pixel.gif\" width=\"1\" height=\"1\">"+
11769     	"</form><br />"+   
11770     	"<div id=\""+instanceId+"_button\">Add To Cart</div><iframe id=\""+instanceId+"_frame\" src=\"index.php\" style=\"width:1000px;height: 1000px;\"></iframe>";
11771     }
11772     this.destroy=function(){
11773     }
11774 }
11775 
11776 WIDGETS.register("KKSchoolProducts", KKSchoolProducts);
11777 
11778 
11779 
11780 
11781 
11782 
11783 function KonfidentKidzSchoolProductWidget(instanceId, data){
11784     this.instanceId = instanceId;
11785     var loadingImId = this.instanceId+"_loading";
11786     var submitButton = new ValidatedSubmitButton(instanceId,data);
11787     var payPalButton = new PayPalBuyNowWidget(instanceId+"_paypal", {showButton: false, productId: data.productId, autoSubmit: false,  optionName: "Age Range", sandboxMode: true});
11788     this.loader=function(){           
11789     	var formDataGroupB = DATA.get(data.formGroup, undefined, {});
11790     	//log("LOADING school products widget");
11791     	F.liftB(function(user){
11792     		log("HOLA!");
11793     		if(!good()){
11794     			return NOT_READY;
11795     		}
11796     		var vars = ["schoolname", "schooladdress", "firstname", "lastname", "contactnumber", "contact_email", "Password", "Email"];
11797     		for(index in vars){
11798     			var name = vars[index];//user.group_id!=1
11799     			log("Sending Event: "+name+"_man");
11800     			DATA.getB(name+"_man").sendEvent({valid: true, value: undefined, name: name});
11801     		}
11802     	}, userB.delayB(2000));
11803     	
11804         var formDataB = formDataGroupB.liftB(function(validationMap){
11805         	//log("FormDataChange");
11806         	if(validationMap==NOT_READY){
11807         		return F.constantB(NOT_READY);
11808         	}
11809             return F.liftB.apply(this,[function(){
11810             	log("INNER FormDataChange");
11811             	var dataOb = {};
11812                // log(arguments);
11813                 for(index in arguments){   
11814                 	log(arguments[index]);
11815                 	if(arguments[index].valid){
11816                         dataOb[arguments[index].name] = arguments[index].value;                            
11817                     }
11818                 }
11819                 return dataOb;
11820             }].concat(getObjectValues(validationMap)));
11821         }).switchB();
11822         
11823     	//var formDataB = F.receiverE().startsWith(NOT_READY);
11824         submitButton.loader();  
11825         payPalButton.loader();
11826         var submitClickedE = jQuery("#"+submitButton.elementId).fj('extEvtE', 'click').snapshotE(formDataB).mapE(function(formData){
11827         	return formData;
11828         });
11829         var submitClickedB = submitClickedE.startsWith(NOT_READY);       
11830         var confirmButtonE = submitClickedE.mapE(function(formData){
11831         	var message = "<div style=\"text-align: center;\">" +
11832         			"<table style=\"margin: 0 auto; text-align: left;\">" +
11833         			"<tr><td>School Name</td><td>"+formData.schoolname+"</td></tr>" +
11834         			"<tr><td>School Address</td><td>"+formData.schooladdress+"</td></tr>" +
11835         			"<tr><td>Contact Name</td><td>"+formData.firstname+" "+formData.lastname+"</td></tr>" +
11836         			"<tr><td>Contact Number</td><td>"+formData.contactnumber+"</td></tr>" +
11837         			"<tr><td>Email Address</td><td>"+formData.Email+"</td></tr>" +
11838         			"<tr><td>Address</td><td>"+formData.schooladdress+"</td></tr>" +
11839         			"</table></div>";
11840         	UI.confirm("Please confirm your data", message, "Confirm Details", function(){
11841         		for(var i=1;i<6;i++){
11842             		if(DOM.get("students_radio_"+i).checked){
11843             			payPalButton.requestInvoice("optionValue="+DOM.get("students_radio_"+i).value);
11844             		}
11845             	}
11846         	}, "Modify Details", function(){
11847         		
11848         	}, false, function(){});
11849         });
11850          
11851         var invoicedFormDataB = F.liftB(function(invoice, formData){
11852         	if(!good()){
11853         		return NOT_READY;
11854         	}
11855         	formData.invoiceId = invoice.invoiceId;
11856         	formData.product = data.productId;
11857         	formData.valid = true;
11858         	formData.optionName = data.optionName;
11859         	
11860         	for(var i=1;i<6;i++){
11861         		if(DOM.get("students_radio_"+i).checked){
11862         			formData.optionValue = DOM.get("students_radio_"+i).value.replaceAll(" or under", "");
11863         			payPalButton.setOptionValue(DOM.get("students_radio_"+i).value);
11864         		}
11865         	}
11866         	return {type: 'post', data: formData, dataType: 'json', url: '/request/KK_registerUser'};
11867         }, payPalButton.invoiceE.startsWith(NOT_READY), formDataB);
11868         
11869         invoicedFormDataB.ajaxRequestB().liftB(function(){
11870         	if(!good()){
11871         		return NOT_READY;
11872         	}
11873         	payPalButton.submit();
11874         });
11875     }
11876     this.build=function(){
11877         return submitButton.build()+payPalButton.build()+"<img id=\""+loadingImId+"\" class=\"loadingSpinner\" src=\"/resources/trans.png\" alt=\"\" />";                 
11878     }
11879 }
11880 WIDGETS.register("KonfidentKidzSchoolProductWidget", KonfidentKidzSchoolProductWidget);
11881 
11882 function kk_deleteInvoice(invoiceId){
11883 	   ajax({
11884 	        dataType: 'json',
11885 	        url: SETTINGS.scriptPath+"request/deleteInvoice/"+invoiceId,
11886 	        success: function(data){
11887 	        	if(data=="OK"){
11888 	        		UI.showMessage("", "Invoice Deleted", function(){}, {modal: true,draggable:false, resizable: false});
11889 	        	}
11890 	        	else{
11891 	        		UI.showMessage("Error", data, function(){}, {modal: true,draggable:false, resizable: false});
11892 	        	}
11893 	        },
11894 	        error: function(){}
11895 	   });
11896 }
11897 
11898 
11899 
11900 function KonfidentKidzManualProductWidget(instanceId, data){
11901     this.loader=function(){           
11902     	/*var formDataGroupB = DATA.get("konfidentkidz_schoolProducts", undefined, {});*/
11903     	//
11904 
11905     	
11906     	var formDataGroupR = DATA.getRemote("konfidentkidz_schoolProducts", undefined, NOT_READY, POLL_RATES.VERY_FAST);
11907     	var formDataGroupB = formDataGroupR.behaviour;
11908     	var productsUpdatedB = formDataGroupB.liftB(function(formDataGroup){
11909     		if(!good()){
11910     			return NOT_READY;
11911     		}
11912     		DOM.get(instanceId+"_product").innerHTML = "";
11913     		for(var index in formDataGroup){
11914     			var product = formDataGroup[index];
11915     			DOM.get(instanceId+"_product").innerHTML += "<option value=\""+product.product_id+"\">"+product.name+"</option>";
11916     		}
11917     		return DOM.get(instanceId+"_product");
11918     	});
11919     	
11920     	var productB = F.extractValueB(instanceId+"_product");
11921     	var schoolnameB = F.extractValueB(instanceId+"_schoolname");
11922     	var schooladdressB = F.extractValueB(instanceId+"_schooladdress");
11923     	var firstnameB = F.extractValueB(instanceId+"_firstname");
11924     	var lastnameB = F.extractValueB(instanceId+"_lastname");
11925     	var emailB = F.extractValueB(instanceId+"_email");
11926     	var passwordB = F.extractValueB(instanceId+"_password");
11927     	var passwordconfirmB = F.extractValueB(instanceId+"_passwordconfirm");
11928     	var submitClickedE = F.extractEventE(instanceId+"_submit", "click");
11929     	
11930     	var dataB = F.liftB(function(product, schoolname, schooladdress, firstname, lastname, email, password, passwordconfirm, productsUpdatedB){
11931     		if(!good()){
11932     			return NOT_READY;
11933     		}
11934     		return {url:"/request/KK_manualPayment", type: "post", data: {product:DOM.get(instanceId+"_product").value, schoolname:schoolname, schooladdress:schooladdress, firstname:firstname, lastname:lastname, email:email, password:password, passwordconfirm:passwordconfirm}, dataType:"json"};
11935     	}, productB, schoolnameB, schooladdressB, firstnameB, lastnameB, emailB, passwordB, passwordconfirmB, productsUpdatedB);
11936     	
11937     	submitClickedE.snapshotE(dataB).filterE(function(request){
11938     		var data = request.data;
11939     		if(data.password!==data.passwordconfirm){
11940     			UI.showMessage("Input Error", "Passwords do not match!");
11941     			return false;
11942     		}
11943     		if(data.firstname.length==0){
11944     			UI.showMessage("Input Error", "Please Specify a first name");
11945     			return false;
11946     		}
11947     		if(data.lastname.length==0){
11948     			UI.showMessage("Input Error", "Please Specify a last name");
11949     			return false;
11950     		}
11951     		if(data.email.length==0){
11952     			UI.showMessage("Input Error", "Please Specify a email address");
11953     			return false;
11954     		}
11955     		if(data.password.length==0){
11956     			UI.showMessage("Input Error", "Please Specify a password");
11957     			return false;
11958     		}
11959     		if(data.schoolname.length==0){
11960     			UI.showMessage("Input Error", "Please Specify a school name");
11961     			return false;
11962     		}
11963     		if(data.schooladdress.length==0){
11964     			UI.showMessage("Input Error", "Please Specify a school address");
11965     			return false;
11966     		}
11967     		return true;
11968     		
11969     	}).ajaxRequestE().mapE(function(data){
11970     		UI.showMessage("", data.message);
11971     	});
11972     }
11973     this.build=function(){
11974         return "<div id=\""+instanceId+"_container\">Product<br /><select id=\""+instanceId+"_product\"></select><br />"+
11975         "School Name<br /><input id=\""+instanceId+"_schoolname\" type=\"text\" /><br />"+
11976         "School Address<br /><textarea id=\""+instanceId+"_schooladdress\" rows=\"5\" cols=\"40\"></textarea><br />"+
11977         "Principal<br />"+
11978         "First Name<br /><input id=\""+instanceId+"_firstname\" type=\"text\" /><br />"+
11979         "Last Name<br /><input id=\""+instanceId+"_lastname\" type=\"text\" /><br />"+
11980         "Email Address<br /><input id=\""+instanceId+"_email\" type=\"text\" /><br />"+
11981         "Password<br /><input id=\""+instanceId+"_password\" type=\"password\" /><br />"+
11982         "Password Confirm<br /><input id=\""+instanceId+"_passwordconfirm\" type=\"password\" /><br />"+
11983         "<input id=\""+instanceId+"_submit\" class=\"button\" type=\"submit\" /></div>";                 
11984     }
11985 }
11986 WIDGETS.register("KonfidentKidzManualProductWidget", KonfidentKidzManualProductWidget);
11987 
11988 /**
11989  *  UsersManagerWidget
11990  * @constructor
11991  */                                               
11992 function KKUsersManagerWidget(instanceId, data){
11993     
11994     this.loader=function(){
11995         var dataR = DATA.getRemote("kk_users", "", NOT_READY, POLL_RATES.VERY_FAST);  //, NOT_READY, POLL_RATES.SLOW
11996         var renderedTableB = F.liftBI(function(data, groups){
11997             if(data==NOT_READY||groups==NOT_READY)
11998                 return NOT_READY;
11999             return data;
12000         },function(value){
12001         	log("kk_users upstream event");
12002         	log(value);
12003             return [value];
12004         }, dataR.behaviour);
12005     
12006     tableB = TableWidgetB(instanceId+"_table", data, renderedTableB);    
12007     F.insertDomB(tableB, instanceId+"_container");
12008     }
12009     this.destroy=function(){
12010         DATA.deregister("kk_users", "");
12011     }
12012     this.build=function(){
12013         return "<span id=\""+instanceId+"_container\"> </span>";
12014     }
12015 }          
12016 WIDGETS.register("KKUsersManagerWidget", KKUsersManagerWidget);   
12017 
12018 
12019 
12020 function SchoolNameInput(instanceId, data){
12021     this.instanceId = instanceId;
12022     this.inputId = instanceId+"_input"   
12023     var visible = (data.visible==undefined)?true:data.visible;
12024     this.loader=function(){       
12025         var formGroupB = DATA.get(data.formGroup, undefined, {});  
12026         var valueName = (data.name==undefined)?"SchoolName":data.name;
12027         
12028         
12029         var mySchoolB = DATA.getRemote("konfidentkidz_myschool").behaviour;        
12030 
12031         var widgetValueB = mySchoolB.liftB(function(school){
12032             if(!good()){
12033             	DOM.get(instanceId+"_input").className = 'form_validator_invalidInput';
12034                 return {valid: false, value: "", name: valueName};
12035             }
12036             
12037             DOM.get(instanceId+"_input").className = 'form_validator_validInput';
12038             DOM.get(instanceId+"_input").value = school.name;
12039             return {valid: true, value: school.name, name: valueName};
12040         });  
12041         pushToValidationGroupBehaviour(instanceId, formGroupB, widgetValueB);  
12042     }      
12043     this.build=function(){
12044         return "<input id=\""+instanceId+"_input\" type=\""+(visible?'text':'hidden')+"\" />";//"<input id=\""+this.inputId+"\" type=\"text\">";         
12045     }
12046 }
12047 WIDGETS.register("SchoolNameInput", SchoolNameInput);
12048 
12049 jQuery(document).ready(function(){
12050     document.body.style.background="url('"+SETTINGS['scriptPath']+"themes/konfidentkidz/background.jpg')";
12051     //jQuery("input:submit, a, button").button();          //, ".button"
12052     jQuery("input:submit").button();
12053     //document.body.style.backgroundAttachement="fixed"; 
12054 });
12055 jQuery(document).ready(function(){
12056     jQuery(document.getElementById("productsImage")).hover(function(){
12057         jQuery("#productsPopup").fadeIn(700);
12058     }, function(){
12059         jQuery("#productsPopup").fadeOut(700);
12060     });
12061 });   
12062 
12063 
12064 
12065   var _gaq = _gaq || [];
12066   _gaq.push(['_setAccount', 'UA-35308071-1']);
12067   _gaq.push(['_trackPageview']);
12068 
12069   (function() {
12070     var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
12071     ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
12072     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
12073   })();
12074 
12075 
12076 ////////////////////////////////////////////////////////////////////////////////////////////
12077 //  Experimental Typed EventStreams
12078 
12079 
12080 var receiverDefinition = {sendEvent: function(value){F.internal_.propagatePulse(new F.internal_.Pulse(F.internal_.nextStamp(), value),evt);}};
12081 function F.checkType = function(value, expectedType){
12082 	if(typeof(value)!='expectedType'){
12083 		log("Error during function "+arguments.callee.caller.name+" expected "+expectedType+" but found "+typeof(value));
12084 	}
12085 }
12086 
12087 
12088 //Number Event Stream
12089 /**
12090  * F.NumberEventStream
12091  * Event: Array Node b * ( (Pulse a -> Void) * Pulse b -> Void)
12092  * @constructor
12093  * @param {Array.<F.EventStream>} nodes
12094  */
12095 F.NumberEventStream = jQuery.extend({
12096 	addE: function(amount){
12097 		return this.mapE(function(value){
12098 			F.checkType(value, 'number');
12099 			return value+amount;
12100 		});
12101 	},
12102 	subtractE: function(amount){
12103 		return this.mapE(function(value){
12104 			F.checkType(value, 'number');
12105 			return value-amount;
12106 		});
12107 	},
12108 	multiplyE: function(amount){
12109 		return this.mapE(function(value){
12110 			F.checkType(value, 'number');
12111 			return value*amount;
12112 		});
12113 	},
12114 	divideE: function(amount){
12115 		return this.mapE(function(value){
12116 			F.checkType(value, 'number');
12117 			return value/amount;
12118 		});
12119 	},
12120 	gtFilterE: function(amount){
12121 		return this.filterE(function(value){
12122 			F.checkType(value, 'number');
12123 			return value>amount;
12124 		});
12125 	},
12126 	ltFilterE: function(amount){
12127 		return this.filterE(function(value){
12128 			F.checkType(value, 'number');
12129 			return value<amount;
12130 		});
12131 	}
12132 }, receiverDefinition, F.EventStream);
12133 
12134 
12135 /** 
12136  * Create an EventStream that has string transformation functions 
12137  * @returns {F.StringEventStream}
12138  */
12139 F.strReceiverE = function() {
12140   return new F.NumberEventStream([],function(pulse) { return pulse; });
12141 };
12142 
12143 /** 
12144  * Convert an EventStream into a StringEventStream
12145  * @returns {F.StringEventStream}
12146  */
12147 F.EventStream.prototype.toNumber() = function() {
12148   return new F.NumberEventStream([this.mapE(function(value){
12149   	F.checkType(value, 'number');
12150   	return (typeof(value)=='string'?parseInt(value), value);
12151   })],function(pulse) { return pulse; });
12152 };
12153 
12154 
12155 
12156 
12157 
12158 
12159 //String Event Streams
12160 /**
12161  * F.StringEventStream
12162  * Event: Array Node b * ( (Pulse a -> Void) * Pulse b -> Void)
12163  * @constructor
12164  * @param {Array.<F.EventStream>} nodes
12165  */
12166 F.StringEventStream = jQuery.extend({
12167 	replaceE: function(search, rep){
12168 		return this.mapE(function(str){
12169 			F.checkType(str, 'string');
12170 			return str.replace(search, rep);
12171 		});
12172 	},
12173 	parseIntE: function(){
12174 		return this.mapE(function(str){	
12175 			F.checkType(str, 'string');
12176 			var numbrVal = parseInt(str);
12177 			F.checkType(numbrVal, 'int');
12178 			return numbrVal;
12179 		}).toNumberE();
12180 	},
12181 	parseJSONE: function(){
12182 		return this.mapE(function(str){
12183 			F.checkType(str, 'string');
12184 			return JSON.parse(str);
12185 		});
12186 	}
12187 }, receiverDefinition, F.EventStream);
12188 
12189 
12190 /** 
12191  * Create an EventStream that has string transformation functions 
12192  * @returns {F.StringEventStream}
12193  */
12194 F.strReceiverE = function() {
12195   return new F.StringEventStream([],function(pulse) { return pulse; });
12196 };
12197 
12198 /** 
12199  * Convert an EventStream into a StringEventStream
12200  * @returns {F.StringEventStream}
12201  */
12202 F.EventStream.prototype.toStringE() = function() {
12203   return new F.StringEventStream([this.mapE(function(value){
12204   	F.checkType(value, 'string');
12205   	return (typeof(value)!='string'?JSON.stringify(value), value);
12206   })],function(pulse) { return pulse; });
12207 };
12208 
12209 
12210 
12211 
12212 //Dom Event Streams
12213 /**
12214  * F.DOMElementEventStream
12215  * Event: Array Node b * ( (Pulse a -> Void) * Pulse b -> Void)
12216  * @constructor
12217  * @param {Array.<F.EventStream>} nodes
12218  */
12219 F.DOMElementEventStream = jQuery.extend({
12220 	index: function(event){
12221 		return this.mapE(function(element){
12222 			return jQuery(element).index();
12223 		}).toNumberE();
12224 	},
12225 	checked: function(event){
12226 		return this.mapE(function(element){
12227 			return element.checked!=undefined && element.checked;
12228 		});
12229 	},
12230 	unchecked: function(event){
12231 		return this.mapE(function(element){
12232 			return element.checked!=undefined && (!element.checked);
12233 		});
12234 	},
12235 	filterCheckedE: function(event){
12236 		return this.filterE(function(element){
12237 			return element.checked!=undefined&&(!element.checked);
12238 		});
12239 	},
12240 	filterUnCheckedE: function(event){
12241 		return this.filterE(function(element){
12242 			return element.checked!=undefined&&(element.checked);
12243 		});
12244 	}
12245 }, receiverDefinition, F.EventStream);
12246 
12247 /** 
12248  * Create an EventStream that has string transformation functions 
12249  * @returns {F.StringEventStream}
12250  */0
12251 F.domReceiverE = function() {
12252   return new F.DOMElementEventStream([],function(pulse) { return pulse; });
12253 };
12254 
12255 /** 
12256  * Create an EventStream that has string transformation functions 
12257  * @returns {F.StringEventStream}
12258  */
12259 F.EventStream.prototype.toDomElementE() = function() {
12260   return new F.DOMElementEventStream([this.mapE(function(value){
12261   	if(value.nodeType==undefined){
12262 		log("Error during function "+arguments.callee.caller.name+" expected DomElement but found "+typeof(value));
12263 	}
12264   	return value;
12265   })],function(pulse) { return pulse; });
12266 };
12267 
12268 
12269 
12270 
12271 //Dom Event Streams
12272 /**
12273  * F.DOMEventStream
12274  * Event: Array Node b * ( (Pulse a -> Void) * Pulse b -> Void)
12275  * @constructor
12276  * @param {Array.<F.EventStream>} nodes
12277  */
12278 F.DOMEventStream = jQuery.extend({
12279 	targetE: function(event){
12280 		return this.mapE(function(event){
12281 			return event.target;
12282 		}).toDomElementE();
12283 	},
12284 	targetIdE: function(event){
12285 		return this.mapE(function(event){
12286 			return event.target.id;
12287 		}).toStringE();
12288 	}
12289 }, receiverDefinition, F.EventStream);
12290 
12291 /** 
12292  * Create an EventStream that has string transformation functions 
12293  * @returns {F.StringEventStream}
12294  */0
12295 F.domReceiverE = function() {
12296   return new F.DOMEventStream([],function(pulse) { return pulse; });
12297 };
12298 
12299 /** 
12300  * Create an EventStream that has string transformation functions 
12301  * @returns {F.StringEventStream}
12302  */
12303 F.EventStream.prototype.toDomE() = function() {
12304   return new F.DOMEventStream([this.mapE(function(value){
12305   	if(value.nodeType==undefined){
12306 		log("Error during function "+arguments.callee.caller.name+" expected DomEvent but found "+typeof(value));
12307 	}
12308   	return value;
12309   })],function(pulse) { return pulse; });
12310 };
12311 
12312 
12313